如果我说包含字段的 Customer 类,我该如何为 Linq 编写动态查询:
string name
string address
int phoneno
我必须根据给出的类似信息进行查询
query = string.Empty;
if(!string.IsNullorEmpty(name))
{
query += "@name = name";
}
if(!string.IsNullorEmpty(address))
{
query += "@address = address";
}
if(!string.IsNullorEmpty(phoneno))
{
query += "@phoneno = phoneno";
}
var result = from condition in customer
where(query)
select condition;
编辑#1:
项目在运行时是可变的
private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
here the attribute may be, name alone, or name and address, or name address and phoneno
foreach(string field in attributes.key)
{
query += field == attributes[key];
}
Customers[] =ExecuteQuery(query);
}
LINQ 支持这种查询吗?
编辑#2:
嗨,穆克,
由于我是 C# 的新手,我仍在苦苦挣扎,这对我不起作用。
var query = _ConfigFile.ConnectionMasterSection;
for(int i = 0; i < filter.count; i++)
{
query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}
这个 yields Empty,我用它的地方
var query = _ConfigFile.ConnectionMasterSection;
//Hard coded
res.Where(q => q.category == filter[0].Value);
它如我所料地工作。
嗨,布莱恩·沃茨,
我也尝试了您的代码,但出现此错误:“Lambda 参数不在范围内”。
for(int i = 0; i < filter.count; i++)
{
Field item = filter[i];
MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));
MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}
try
{
var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}
这里有什么错误?
最佳答案
看看这个 http://www.albahari.com/nutshell/predicatebuilder.aspx ,它允许强类型谓词构建,它真的很棒。如果您实际上想要动态字符串构建谓词,则可以使用 LINQ Dynamic Query Library由 ScottGu 提供。
虽然我会在第二个选项之前推荐第一个选项,但两者都会完成您想要的。
允许你做:
var predicate = PredicateBuilder.True<MyLinqType>();
if(!string.IsNullOrEmpty(name))
predicate = predicate.And(p => p.name == name);
...
var myResults = Context.MyLinTypeQueryTable.Where(predicate);
还有更多。
关于c# - LINQ 中的动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/621466/