如何将 OR 运算符动态添加到 LINQ 中的 WHERE 子句 [英] How to dynamically add OR operator to WHERE clause in LINQ
问题描述
我有一个可变大小的字符串数组,我试图以编程方式遍历该数组并匹配表中的所有行,其中Tags"列至少包含数组中的一个字符串.下面是一些伪代码:
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"));
但是,这不起作用(我收到以下错误:带有语句体的 lambda 表达式无法转换为表达式树")
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;
});
谁能告诉我实现这一目标的正确策略?我对 LINQ 的世界还是陌生的 :-)
Can anybody show me the correct strategy to accomplish this? I am still new to the world of LINQ :-)
推荐答案
您可以使用 PredicateBuilder
类:
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);
这篇关于如何将 OR 运算符动态添加到 LINQ 中的 WHERE 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!