0

I am using jqgrid in MVC 4. I have written a method for getting a list in linq. In my function I am getting all values of jqgrid with search criteria i.e. Operator AND/OR , operations Equals to, not equals to etc. Here I am also getting the column name like Name, City, State etc.

My problem is I can't pass the column name directly in linq query i.e. I have to use the column name as x => x.Name

switch (rule.field)
{
    case "Name":
    query = query.Where(x => x.Name.StartsWith(rule.data, StringComparison.OrdinalIgnoreCase));
    break;

    case "Course":
    query = query.Where(x => x.Course.StartsWith(rule.data, StringComparison.OrdinalIgnoreCase));
    break;
}

In rule.field I am getting column Name i.e. Name, city, state etc. I want to pass the column name which I am getting in rule.filed in LINQ query instead of x =>x.Name.

Is there any way to do it so I can avoid writing switch cases?

Jace Rhea
  • 4,982
  • 4
  • 36
  • 55
Learner
  • 59
  • 1
  • 7

2 Answers2

0

You could always use reflection:

query = query.ToList().Where(p => {
    var field = p.GetType().GetProperty(rule.field);
    var value = (String) field.GetValue(p);
    return value.StartsWith(rule.data, StringComparison.OrdinalIgnoreCase);
});

Warning: Reflection is slow. Only use this for short lists. Since you're dealing with UI rendering, I'm assuming this won't be a problem.

edit: My example is assuming all properties are indeed properties (and not fields), and that all properties are Strings. You may need to alter the code for your specific case.

Nilzor
  • 18,082
  • 22
  • 100
  • 167
  • I am getting error like "A lambda expression with a statement body cannot be converted to an expression tree" – Learner Jan 06 '14 at 07:00
  • Answer modified with `ToList()` to ensure that the query-object is queryable. See http://stackoverflow.com/questions/5179341/a-lambda-expression-with-a-statement-body-cannot-be-converted-to-an-expression for related question if this does not work either. (I don't know what type of object `query` is at your end. I assumed it was some kind of `IQueryable`) – Nilzor Jan 06 '14 at 11:21
0

You can use System.Linq.Dynamic, which can be installed as a Nuget package along with string.Format. The syntax would then look something like..

 var newquery = query.AsQueryable()
            .Where(
                string.Format("{0}.ToUpper().StartsWith(@0)", rule.field)
                    ,rule.data.ToUpper());
Original10
  • 572
  • 3
  • 8