如何在LINQ中动态添加OR运算符到WHERE子句 [英] How to dynamically add OR operator to WHERE clause in LINQ
问题描述
IQueryable< Songs> allSongMatches = musicDb.Songs; //表中的所有行
我可以轻松地查询一个固定的字符串集,如下所示:
allSongMatches = allSongMatches.Where(SongsVar => SongsVar.Tags.Contains(foo1)|| SongsVar .Tags.Contains(foo2)|| SongsVar.Tags.Contains(foo3));
但是,这不起作用(我得到以下错误:具有语句正文的lambda表达式不能转换为表达式树)
allSongMatches = allSongMatches.Where(SongsVar =>
{
bool retVal = false;
foreach(strArray中的字符串str)
{
retVal = retVal || SongsVar.Tags.Contains(str);
}
return retVal;
});
有谁能告诉我正确的策略来完成这个?我仍然是LINQ的世界新人: - )
你可以使用 PredicateBuilder
类:
var searchPredicate = PredicateBuilder.False< Songs>();
foreach(strArray中的字符串str)
{
var closureVariable = str; //查看以下链接的原因
searchPredicate =
searchPredicate.Or(SongsVar => SongsVar.Tags.Contains(closureVariable));
}
var allSongMatches = db.Songs.Where(searchPredicate);
I have a variable size array of strings, and I am trying to programatically loop through the array and match all the rows in a table where the column "Tags" contains at least one of the strings in the array. Here is some pseudo code:
IQueryable<Songs> allSongMatches = musicDb.Songs; // all rows in the table
I can easily query this table filtering on a fixed set of strings, like this:
allSongMatches=allSongMatches.Where(SongsVar => SongsVar.Tags.Contains("foo1") || SongsVar.Tags.Contains("foo2") || SongsVar.Tags.Contains("foo3"));
However, this does not work (I get the following error: "A lambda expression with a statement body cannot be converted to an expression tree")
allSongMatches = allSongMatches.Where(SongsVar =>
{
bool retVal = false;
foreach(string str in strArray)
{
retVal = retVal || SongsVar.Tags.Contains(str);
}
return retVal;
});
Can anybody show me the correct strategy to accomplish this? I am still new to the world of LINQ :-)
You can use the PredicateBuilder
class:
var searchPredicate = PredicateBuilder.False<Songs>();
foreach(string str in strArray)
{
var closureVariable = str; // See the link below for the reason
searchPredicate =
searchPredicate.Or(SongsVar => SongsVar.Tags.Contains(closureVariable));
}
var allSongMatches = db.Songs.Where(searchPredicate);
这篇关于如何在LINQ中动态添加OR运算符到WHERE子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!