<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1070</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1070" rel="self"/>
  <title>Torbj&#195;&#184;rn</title>
  <updated>Thu Nov 12 11:43:12 -0800 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1097</id>
    <published>2009-11-12T11:43:12-08:00</published>
    <updated>2009-11-16T08:57:50-08:00</updated>
    <title>[C#] Generic Linq where clause ORing together many</title>
    <content type="html">&lt;p&gt;Suddenly found myself having written this piece of ugly Extension method, and I'm wondering if there is a more clear way of doing this.&lt;/p&gt;

&lt;p&gt;The idea is that given a list of objects, I want to generate the where expression/func that will give me all rows in the database (TDbTable), and I have a comparison that will match TEntity to TDbTable. In reality it generates this kind of SQL: &amp;quot;WHERE id = 1 or id = 2 or id = 3 ... &amp;quot;&lt;/p&gt;

&lt;pre&gt;        public static Func&amp;lt;TDbTable, bool&amp;gt; GetWhereClauseForAll&amp;lt;TDbTable, TEntity&amp;gt;(
            this List&amp;lt;TEntity&amp;gt; objects,
            Func&amp;lt;TEntity, Func&amp;lt;TDbTable, bool&amp;gt;&amp;gt; comparison)
        {
            Func&amp;lt;Func&amp;lt;TDbTable, bool&amp;gt;, Func&amp;lt;TDbTable, bool&amp;gt;, Func&amp;lt;TDbTable, bool&amp;gt;&amp;gt; concatWhereClauses
                = (existingWhereClause, toBeAddedWhereClause)
                    =&amp;gt; row
                    =&amp;gt; existingWhereClause(row) || toBeAddedWhereClause(row);

            Func&amp;lt;TDbTable, bool&amp;gt; whereClause = comparison(objects.First());

            for (int i = 1; i &amp;lt; objects.Count; i++)
                whereClause = concatWhereClauses(whereClause, comparison(objects[i]));

            return whereClause;
        }&lt;/pre&gt;</content>
    <author>
      <name>Torbj&#195;&#184;rn</name>
      <email>torbjorn.maro@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1097-generic-linq-where-clause-oring-together-many" rel="alternate"/>
  </entry>
</feed>

