C# Tips: IEnumerable<T>.ForEach extension method
January 13, 2010 Leave a comment
I’m sure everyone have already used IEnumerable<T> extension methods to query your .NET collections.
Well, one thing we usually do is loop through a collection’s items and do something.
Lets say I want to write some data about portuguese people I find in my persons collection and then retrieve the maximum age value to do something else:
void Work() { var persons = RetrievePersons(); var portuguesePeople = persons.Where(p => p.Country == "Portugal"); int maxAge; foreach (var p in persons.Where(p => p.Country == "Portugal")) Console.WriteLine("Name: {0} ; Age: {1}", p.Name, p.Age); maxAge = portuguesePeople.Max(p => p.Age); //... }
Because the foreach statement can’t be used in a fluent API (eg. Linq) we need an extra reference so the portuguese results we’re looping through can be reused when retrieving the max age value. Being able to write code in a fluent API makes it easier to read and reduces the number of (sometimes unnecessary) variables in your code.
C# has a ForEach instance method for List<T> but most of the times you will be dealing with IEnumerable<T> references, so a ForEach extension method would be handy in these cases.
