LINQ rules!

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! 🙂

Über Stefan

Polyglot Clean Code Developer

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax