在LINQ中使用字符串作为字段名称

Kri*_*s-I 9 c# linq linq-to-objects linq-to-sql

看下面的代码.我想用USERNAME参数中收到的字段名替换field.此方法必须能够在多个字段上进行一些搜索.

谢谢,

public void Searching(string field, string stringToSearch)
{
    var res = 
        from user in _dataContext.USERs where 
        user.USERNAME.Contains(stringToSearch)
        select new 
        {
          Id = user.ID,
          Username = user.USERNAME
        };

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 15

你需要忘记匿名类型,也许可以使用Tuple<int,string>; 但是:怎么样:

IQueryable<Foo> source = // YOUR SOURCE HERE
      // in-memory dummy example:
      // source = new[] {
      //    new Foo {Id = 1, Bar = "abc"},
      //    new Foo {Id = 2, Bar = "def"}
      // }.AsQueryable();

string field = "Bar";
string stringToSearch = "d";
var param = Expression.Parameter(typeof (Foo), "x");
var predicate = Expression.Lambda<Func<Foo, bool>>(
    Expression.Call(
        Expression.PropertyOrField(param, field),
        "Contains", null, Expression.Constant(stringToSearch)
    ), param);
var projection = Expression.Lambda<Func<Foo, Tuple<int, string>>>(
    Expression.Call(typeof(Tuple), "Create", new[] {typeof(int), typeof(string)},
        Expression.PropertyOrField(param, "Id"),
        Expression.PropertyOrField(param, field)), param);
Tuple<int,string>[] data = source.Where(predicate).Select(projection).ToArray();
Run Code Online (Sandbox Code Playgroud)

  • 可爱可爱的B-) (2认同)