如果我说Customer字段包含字段,我如何为Linq编写动态查询:
string name
string address
int phoneno
Run Code Online (Sandbox Code Playgroud)
我必须根据类似的信息进行查询
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;
Run Code Online (Sandbox Code Playgroud)
编辑#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);
}
Run Code Online (Sandbox Code Playgroud)
LINQ是否支持这种查询?
编辑#2:
嗨Mouk,
因为我是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);
}
Run Code Online (Sandbox Code Playgroud)
这是空的,我用这个
var query = _ConfigFile.ConnectionMasterSection;
//Hard coded
res.Where(q => q.category == filter[0].Value);
Run Code Online (Sandbox Code Playgroud)
它按预期工作.
嗨Bryan Watts,
我也尝试了你的代码,我收到了这个错误:"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")));
}
Run Code Online (Sandbox Code Playgroud)
这里有什么错误?
看看这个http://www.albahari.com/nutshell/predicatebuilder.aspx,它允许强类型谓词构建,它可以非常好.如果您想要实际使用动态字符串构建谓词,那么您可以使用ScottGu提供的LINQ Dynamic Query Library.
虽然我会在第二个选项之前推荐第一个选项,但两者都能达到你想要的效果.
允许你这样做:
var predicate = PredicateBuilder.True<MyLinqType>();
if(!string.IsNullOrEmpty(name))
predicate = predicate.And(p => p.name == name);
...
var myResults = Context.MyLinTypeQueryTable.Where(predicate);
Run Code Online (Sandbox Code Playgroud)
和更多.