如何将 OR 运算符动态添加到 LINQ 中的 WHERE 子句 [英] How to dynamically add OR operator to WHERE clause in LINQ

查看:35
本文介绍了如何将 OR 运算符动态添加到 LINQ 中的 WHERE 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变大小的字符串数组,我试图以编程方式遍历该数组并匹配表中的所有行,其中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);

LinqToSql 奇怪的行为

这篇关于如何将 OR 运算符动态添加到 LINQ 中的 WHERE 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆