简体   繁体   English

如何使用List <>作为Linq的where子句的条件?

[英]How can I use a List<> as the condition for my where clause with Linq?

So I've been banging my head against the proverbial wall for a few hours and I thought I'd see if anybody else has solved this problem before... 所以我已经把头撞在那堵谚语的墙上好几个小时了,我想我想看看是否有人能解决这个问题……

I have a List<string> of values that I want to use as filters on a search. 我有一个想要用作搜索过滤器的值的List<string> In the olden days I would build a string of WHERE field = 'a' OR field = 'b' OR field = 'C' into the query. 在过去,我会在WHERE field = 'a' OR field = 'b' OR field = 'C'构建一个WHERE field = 'a' OR field = 'b' OR field = 'C'的字符串。 But with Linq building that long WHERE clause is rather difficult. 但是随着Linq的建立,那么较长的WHERE子句相当困难。 What I was hoping would work was: 我希望能工作的是:

var results = from x in x.table
              where x.Equals(List<string>)
              select x;

Alas, the compiler isn't smart enough to break down the List<> into a WHERE field = 'a' OR field ='b' kind of query. las,编译器不够聪明,无法将List <>分解为WHERE field = 'a' OR field ='b'类型的查询。 I've moved ahead with this process as a foreach loop on the List<string> but it's pushing processing to the client when I want that part of the execution to take place on the SQL Server. 我已经在List<string>上以foreach循环的方式进行了此过程,但是当我希望执行的那一部分在SQL Server上进行时,它会将处理推送到客户端。 Am I living in fantasy land here or is there a way to make this happen? 我是住在这里的幻想世界还是有办法实现这一目标?

You can use Contains() 您可以使用Contains()

List<string> yourList = new List<string> { "A", "B", "C" };

var results = from x in x.table
              where yourList.Contains(x)
              select x;

If it's Linq to SQL it will generate a WHERE field IN ('A', 'B', 'C') clause. 如果是SQL的Linq,它将生成WHERE field IN ('A', 'B', 'C')子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM