18 October 2007

C#: Using foreach with an generic list (List<t>)

The List is a fantastic class for working with lists and arrays in C#, but it does not directly expose an iEnumerator to allow the foreach command to iterate through the collection. Until today, I would use the for...next structure to cycle through the collection to access each item.

The List also exposes a ForEach method which delegates the ForEach to another method. This is good for some applications that need to share the functionality - and while I understand the use from an OO perspective - can decrease the readability of the code.

There is a better way that can make the code readable and exposes the iEnumerable method.

The List method also exposes the ToArray() method. Use this method to access the items in the collection. For instance, if you have a List<t> called strings, you can write the code as follows:

foreach(string s in strings.ToArray()) { ...looping code here... }