title: LinQ query - Add Where dynamically
body: <p>I am having a hard time solving this problem,  need code for creating a dynamic linq query in C#, asp.net.  I have 5 dropdown list that searches different column in same database table and return item filtered value to a single listbox.  The problem is there is no sequence that which or all or any will be selected in DDLs but the combined filtered result should show up in listbox. I have a working query that is searching and returning result in one column at a time for each DDL selection separately. Have to add where clauses with AND to add other DDL selections dynamically to this query. Thanks</p>
  
  <hr>
  
  <pre><code>public ListItemCollection searchProject(ListItemCollection projList, String searchstr, String columnName)
  {
      DataSet DSToReturn = new DataSet();
  
      ListItemCollection returnItems = new ListItemCollection();
      DataTable results = (from d in ((DataSet)_MyDataset).Tables["Records"].AsEnumerable()
                           orderby d.Field&lt;string&gt;("Name") ascending
                           where (d.Field&lt;string&gt;(columnName) != null)
                           where d[columnName].ToString().ToLower().Contains(searchstr.ToLower())
                           select d).CopyToDataTable();
  
      foreach (ListItem li in projList)
      {
          if ((from System.Data.DataRow row in results.Rows
               where li.Value.Equals(row["value"].ToString(), StringComparison.InvariantCultureIgnoreCase)
               select row["value"]).Count() &gt; 0)
          returnItems.Add(li);
      }
  
      return returnItems;
  }
  </code></pre>