8/13/2010

LINQ THINK

The more I use LINQ, the more I run into legacy code that can easily be improved. The nice thing about LINQ is that it can make your code more elegant and easier to understand, as well as, in most cases, more efficient.

Let’s take a simple  example. Here I’ve extracted some legacy code in the form of a method that tells you if a given string “Key” is present in a string array. First, the “OLD” way:
//"OLD" way:
static bool IsKeyInArray(string[] items, string key)
{
if (items == null) return false;
if (items.Length < 1) return false;
if (String.IsNullOrEmpty(key)) return false;
foreach (string item in items)
{
if (item.Trim() == key)
{
return true;
}
}
return false;
}


The obvious  thing to see here is that we have to iterate over the entire array. Now the new “LINQY” way:


static bool IsKeyInArray2(string[] items, string key)
{
bool isInArray = false;
if (items == null || items.Length <1 || String.IsNullOrEmpty( key)) 
return false;
if (items.ToList().Contains(key))
isInArray = true;
return isInArray;
}


Note that by simply calling the ToList() extension method, we’ve automatically converted our string array into a “LINQY” construct. No iteration needed, just use the “Contains( key)” method.