Lambda Expression Optimizations

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 myObjs  = new List<MyObject>();
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 class GenericExtensions
{
    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:

var myObjs  = new List<MyObject>();
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.

Advertisement

About Kevin K. Nelson
I am a business owner/programmer by trade, but my heart is in teaching and writing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.