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

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

问题描述

我有一个可变大小的字符串数组,我试图通过编程循环遍历数组,并匹配表中的所有行,其中Tags列至少包含数组中的一个字符串。这是一些伪代码:

  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);

LinqToSql奇怪的行为


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);

LinqToSql strange behaviour

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

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