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:

  1. private string getWhereClauseForTablePrefixes(IList<String> tablePrefixes)
  2. {
  3.     var where = "";
  4.     if (tablePrefixes.Count > 0)
  5.     {
  6.         where += " where ";
  7.         var enumerator = tablePrefixes.GetEnumerator();
  8.         enumerator.MoveNext();
  9.         while (true)
  10.         {
  11.             where += "table_name like ‚" + enumerator.Current + "%’";
  12.             if (enumerator.MoveNext())
  13.             {
  14.                 where += " or ";
  15.             }
  16.             else
  17.             {
  18.                 break;
  19.             }
  20.         }
  21.     }
  22.     return where;
  23. }

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:

  1. private string getWhereClauseForTablePrefixes(IList<String> tablePrefixes)
  2. {
  3.     var where = "";
  4.     if (tablePrefixes.Count > 0)
  5.     {
  6.         where += " where ";
  7.         where += String.Join(" OR ", tablePrefixes.Select(prefix => "table_name like ‚" + prefix + "%’"));
  8.     }
  9.     return where;
  10. }

Simple and concise! 🙂

Ăśber uns 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