使用字符串作为LINQ字段名 [英] Use string as field name in LINQ
本文介绍了使用字符串作为LINQ字段名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看下面的代码。我想通过在参数中收到的字段名称来代替 USERNAME
字段
。这种方法必须能够对多个领域的一些搜索。
感谢,
公共无效搜索(串场,串stringToSearch)
{
VAR解析度=从用户那里_dataContext.USERs
user.USERNAME.Contains(stringToSearch)$
b $ b。选择所需新的
{
n = user.ID,
=用户名user.USERNAME
};
}
解决方案
您需要忘掉匿名类型,也许使用元组LT; INT,串>
代替;但是:怎么样:
的IQueryable<富>来源= //源HERE
//在内存中虚拟的例子:
//源=新[] {
//新的Foo {ID = 1,酒吧=ABC} ,
//新的Foo {ID = 2,酒吧=高清}
//} .AsQueryable();
串场=酒吧;
串stringToSearch =D;
变种参数= Expression.Parameter(typeof运算(美孚),×);
VAR谓词= Expression.Lambda< Func键<富,布尔>>(
Expression.Call(
Expression.PropertyOrField(参数,场),
包含空,Expression.Constant(stringToSearch)
),参数);
VAR投影= Expression.Lambda< Func键<富,元组LT; INT,串>>>(
Expression.Call(typeof运算(元组),创建,新的[] {typeof运算(INT ),typeof运算(字符串)},
Expression.PropertyOrField(参数,ID),
Expression.PropertyOrField(参数,场)),参数);
元组LT; INT,串> []数据= source.Where(谓语)。选择(投影).ToArray();
Look the code below. I'd like to replace USERNAME
by the field name received in the parameter field
. This method must be able to make some search on several fields.
Thank,
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
};
}
解决方案
You need to forget about the anonymous type, maybe use Tuple<int,string>
instead; but: how about:
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();
这篇关于使用字符串作为LINQ字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文