LINQ where condition with dynamic column

一曲冷凌霜 提交于 2020-01-30 06:56:05

问题


I have this code

// IQueryable<General> query

if (columnName == "Column1") 
{
  query = query.Where(x => x.Column1 == searchValue);
}
else if (columnName == "Column2") 
{
  query = query.Where(x => x.Column2 == searchValue);
}
else if (columnName == "Column3") 
{
  query = query.Where(x => x.Column3 == searchValue);
}
else if (columnName == "Column4") 
{
  query = query.Where(x => x.Column4 == searchValue);
}
// next zilions columns to come
// ...

and my question is. How can i past x.Column as a parameter inside ".Where" condition ?


回答1:


You can create a predicate manually. Use this method:

public static Expression<Func<General, bool>> CreatePredicate(string columnName, object searchValue)
{
    var xType = typeof(General);
    var x = Expression.Parameter(xType, "x");
    var column = xType.GetProperties().FirstOrDefault(p => p.Name == columnName);

    var body = column == null
        ? (Expression) Expression.Constant(true)
        : Expression.Equal(
            Expression.PropertyOrField(x, columnName),
            Expression.Constant(searchValue));

    return Expression.Lambda<Func<General, bool>>(body, x);
}

Now you can apply your predicate:

IQueryable<General> query = //
var predicate = CreatePredicate(columnName , searchValue);
query = query.Where(predicate);



回答2:


You can either use Reflection to retrieve the property via name

x.GetType().GetProperty(propertyName,BindingFlags).SetValue(x,value)
// propertyName = "Column1" for example
// BindingFlags are most likely Instance, Public and Property (IIRC)

or pass in the PropertyInfo directly into the method as a parameter. Your choice depends on the abstraction level you want to expose to consumers of your method.




回答3:


You could use reflection and extension methods. As a rough example:

public class Foo
{
  public int Column1 { get; set; }
  public int Column2 { get; set; }
  ...
}

public static class FooExtensions
{
  // I would use the actual type here instead of object if you know the type.
  public static object GetProperyValue(this Foo foo, string columnName)
  {
    var propertyInfo = foo.GetType().GetProperty(columnName);
    var value = propertyInfo.GetValue(foo);
    // as well as cast value to the type
    return value;
  }
}

...

query = query.Where(x => x.GetProperyValue(columnName) == searchValue);
...

As a side note, that is not a well-designed query because every time you add a column to your model, you'd need to update your if-else. It violates the O in SOLID.



来源:https://stackoverflow.com/questions/52967031/linq-where-condition-with-dynamic-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!