user424244
user424244

Reputation: 11

Dynamicallly building Linq "where" clause

I am trying to do something that can be done conventionally by writing extra lines of code. I have seen few samples on this website that addresses my question but still i cannot put all the pieces together to solve what I am trying to achieve.

Here is pseudo code of what i am trying to do:

list<t> searchTerms;

class t
{
string columnName;
string columnValue ;
string columnType ;
 string FilterType;
}

I am using Linq to SQL to retrive data from my database and would like to build the "where" clause with list:

so something like:

SearchTerm t = terms.Find(term => term.ColumnValue == "PartNo");
if (t != null)
{
  switch (t.FilterType)
  {
    case FilterType.Contains:
      q = q.Where(c => c.PartNo.Contains(t.Value));
      break;

    case FilterType.EqualTo:
      q = q.Where(c => c.PartNo.Equals(t.Value));
      break;

    case FilterType.StartsWith:
      q = q.Where(c => c.PartNo.StartsWith(t.Value));
      break;
  }
}

t = terms.Find(term => term.ColumnValue == "ItemDesc");
if (t != null)
{
  switch (t.FilterType)
  {
    case FilterType.Contains:
      q = q.Where(c => c.ItemDesc.Contains(t.Value));
      break;

    case FilterType.EqualTo:
      q = q.Where(c => c.ItemDesc.Equals(t.Value));
      break;

    case FilterType.StartsWith:
      q = q.Where(c => c.ItemDesc.StartsWith(t.Value));
      break;
  }
}

what i would like to do is use lambda expressions/reflection to achieve something like:

q.whereJoinExpression(searchTerms.ToLamdaExpression());

where searchTerms.ToLamdaExpression()

should return me the input for where clause i.e Expression>. and whereJoinExpression should get me same result as

 q = q.Where(searchTerms.ToLamdaExpression());

I have invested a couple of days researching before posting this question and would appreciate help in the right direction.

Upvotes: 1

Views: 2032

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180787

Have a look at Dynamic Linq and Predicate Builder.

Upvotes: 3

Related Questions