Tuesday, September 8, 2009

LINQing away boilerplate collection transformations

Forcing a list of strings to upper case before LINQ:

List<string> list = new List<string> { "element1", "element2", "element3" };
List<string> listCopy = new List<string>();

foreach (string listElement in list)
listCopy.Add(listElement.ToUpper());

foreach (string upperCaseListElement in listCopy)
{
// ...
}






Since LINQ supports transforming sequences inline this can be represented much more succinctly with the following:




foreach (string upperCaseElement in list.Select(el => el.ToUpper()))
{
// ...
}






This expressivity is enabled by C#3.0 support for lambda expressions and the standard query operators.

No comments :

Post a Comment