Iterating List <T>

A question popped up on the C# group that covered something very nicely:
How can you iterate (foreach) over a Generic List?

If you're using List<> then iteration should be fine - List<> has
GetEnumerator() defined.

Using a list

List<FooClass> MyList = SomeBarFunctionThatReturnsAList();

Foreach(FooClass foo in MyList)
{
doSomethingWith(foo);
}



If you're using a custom collection class that you made
yourself, then it needs to implement the IEnumerable interface, which
is a lot easier than it sounds.

To implement IEnumerable, you just implement GetEnumerator, and then you
get to play with the new "Yield Return" statement,which automatically
wraps the method in an enumerator object.

Using a custom class that wraps around a List<>

private List<FooClass> myList;

public IEnumerator GetEnumerator()
{
foreach (foo in myList)
{
yield return foo;
}
}

This message has been brought to you by the words Foo and Bar.

Comments

Popular posts from this blog

Some observations on Script Callbacks, "AJAX", "ATLAS" "AHAB" and where it's all going.

IE7 - Vista: "Internet Explorer has stopped Working"

FIREFOX / IE Word-Wrap, Word-Break, TABLES FIX