Lambda Expression Optimizations
2010.10.21 Leave a Comment
I really love .NET’s ability for extension methods, LINQ, and lambda syntax…I have found that using them can reduce many methods down to a single line, and often make them much clearer at the same time. As an example, have you ever had to loop through a list and create a delimited string? For an array of string[], you can simply using String.Join. However, what if you are looping through an object and concatenating the result of a method call? E.g.
var builder = new StringBuilder();
foreach( var obj in myObjs )
{
if( builder.Length > 0 ) builder.Append( ", " );
builder.Append( Decrypt(obj.BankAccountNumber) );
}
return builder.ToString();
This is some bogus code…the list would always be empty…but assume myObjs actually does contain a list of items in it. We could use an extension method that would allow us to build a delimited string from ANY enumerable list of objects or strings.
{
public static String Implode<T>( this IEnumerable<T> list, String delimiter, Func<T,String> func )
{
var builder = new StringBuilder();
foreach( T item in list )
{
if( builder.Length > 0 ) builder.Append( delimiter );
builder.Append( func( item ) );
}
return builder.ToString();
}
}
The above extension method would allow us to change the first code example to the following:
return myObjs.Implode( ", ", x => Decrypt( x.BankAccountNumber ) );
And the best thing, is this can be used with pretty much any enumerable list/array, so you only have to write it once.