views:

64

answers:

1

Hi, 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 "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 lamdaexpressions/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 couple of days researching before posting this question and would appreciate help in the right direction.

Thanks sharmasu.

+2  A: 

Have a look at Dynamic Linq and Predicate Builder.

Robert Harvey
But Dynamic LINQ loses all the benefits of strong typing and always seems like a cop-out solution. Something like the PredicateBuilder would be nicer, if it could be made to work.
Dan Diplo
Yup thats what i am struggling with
@sharmasu: In a dynamic query situation, typically a user would be building the query from strings anyway (selecting fields from a dropdown, for example), so I don't see how strong typing helps.
Robert Harvey