Here’s an example of a small refactoring I did today using LINQ’s features in C#. I had this method that simply constructs a WHERE clause for a SQL statement using an IList of table prefixes:
private string getWhereClauseForTablePrefixes(IList<String> tablePrefixes)
{
var where = "";
if (tablePrefixes.Count > 0)
{
where += " where ";
var enumerator = tablePrefixes.GetEnumerator();
enumerator.MoveNext();
while (true)
{
where += "table_name like '" + enumerator.Current + "%'";
if (enumerator.MoveNext())
{
where += " or ";
}
else
{
break;
}
}
}
return where;
}
So, e.g. for a list containing A and B the method returned where table_name like 'A%' or table_name like 'B%'. Using the Select extension method on IList, the method now looks like this:
private string getWhereClauseForTablePrefixes(IList<String> tablePrefixes)
{
var where = "";
if (tablePrefixes.Count > 0)
{
where += " where ";
where += String.Join(" OR ", tablePrefixes.Select(prefix => "table_name like '" + prefix + "%'"));
}
return where;
}
Simple and concise! 🙂