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

时间:2012-06-26 09:54:39

标签: c# linq linq-to-sql linq-to-objects

查看下面的代码。我想将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
        };

}

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:4)

事实上,可以使用Expression API:

public void Searching(Expression<Func<User,string>> field, string stringToSearch)
{

   var call = Expression.Call(field.Body, typeof (string).GetMethod("Contains"), new[] {Expression.Constant(value)});
   Expression<Func<User, bool>> exp = Expression.Lambda<Func<User, bool>>(Expression.Equal(call, Expression.Constant(true)), field.Parameters);


    var res =  _dataContext.USERs.Where(exp).Select(u=>new { id= u.ID, Username = u.USERNAME});

}

答案 2 :(得分:3)

你正在尝试的是不可能的。但是,您可以使用dynamic linq library来实现您想要的目标