views:

62

answers:

5

I'm creating a list of my defined objects like so

List<clock> cclocks = new List<clocks>();

for each object in the list i'm calling a method moveTime, like so

foreach(clock c in cclocks)
{
    c.moveTime();
}

is the a way i can write some cleaver thing so i can call

cclocks.moveTime();

it would then go though the list doing that method

I guess I want to create a collection method?

I'm guessing there must be some thing I can do I just don't know what.

thanks for your help

+3  A: 

I'm not quite sure but perhaps you are talking about ForEach() method of List<T>

cclocks.ForEach(c => c.MoveTime());
Andrei Taptunov
+1  A: 

You could write an extension method to do this.

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Paolo
+3  A: 

You could write an extension method on List<T> which iterates this and calls moveTime() on each of the items in the collection. See this article for more information.

This approach obscures a lot of information, though. If I we're you, I'd go with the for-loop. And if you're just calling one method on each of the objects, you can shorten the for-loop, like so:

// no need to declare scope if you're just doing one operation on the collection
foreach(var object in collection) object.method();

... Or use LINQ:

collection.ForEach(object => object.method());
roosteronacid
A: 

You can either create a class that inherits from

List<clock>

or create an extension method for List<clock>

Foxfire
A: 

Another solution is to derive new class from List<Clock> and then add all the methods you need. Something like this:

public class ClocksList : List<Clock>
{
   public void MoveSingleClock(Clock clock)
   {
      clock.MoveTime();
   }

   public void MoveAllClocks()
   {
      foreach(clock c in InnerList)
      {
         MoveSingleClock(c);
      }      
   }
}

You can use new class like this:

ClocksList clocks = new ClocksList();

// Fill the list
clocks.Add(new Clock());
...
// Move time on all clocks
clocks.MoveAllClocks();

// Move single clock
Clock c = new Clock();
clocks.Add(c);
clocks.MoveSingleClock(c);
zendar