Reputation: 1364
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
Upvotes: 0
Views: 183
Reputation: 13562
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);
Upvotes: 0
Reputation: 21727
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());
Upvotes: 3
Reputation: 9495
I'm not quite sure but perhaps you are talking about ForEach()
method of List<T>
cclocks.ForEach(c => c.MoveTime());
Upvotes: 3
Reputation: 5755
You can either create a class that inherits from
List<clock>
or create an extension method for List<clock>
Upvotes: 0
Reputation: 22638
You could write an extension method to do this.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
Upvotes: 1