July 29, 2009

Extension Methods On IEnumerable

The 'System.Linq' namespace adds a bunch of useful IEnumerable extension methods. These are used in Linq expressions but can alos be used seperately.

A reference to the 'System.Core' assembly is required. For example performing a count with an enumerator:
using System.Linq;
//This saves performing a foreach statement on the enumeration and counting the number of elements
IEnumerable enumKeywords = editor.Sections.RunSpec.GetAll("SMOG");
bool metricUnits = enumKeywords.Count() > 0;
// or
bool metricUnits = editor.Sections.RunSpec.GetAll("SMOG").Count() > 0;
// or (even shorter)
bool metricUnits = editor.Sections.RunSpec.GetAll("SMOG").Any();
There are lots of other useful extensions 'ToList', 'Cast', 'Contains', 'OfType', 'First', 'Last', 'Reverse', 'Union', 'Intersect', 'Aggregate', 'Average', ... For more information, try the following Search