Linq to SQL 如何做“where [column] in (list of values)" [英] Linq to SQL how to do "where [column] in (list of values)"

查看:16
本文介绍了Linq to SQL 如何做“where [column] in (list of values)"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以获取一个 id 列表,我需要返回一个与该 id 关联的描述匹配的列表.例如:

I have a function where I get a list of ids, and I need to return the a list matching a description that is associated with the id. E.g.:

public class CodeData
{
    string CodeId {get; set;}
    string Description {get; set;}
}

public List<CodeData> GetCodeDescriptionList(List<string> codeIDs)
    //Given the list of institution codes, return a list of CodeData
    //having the given CodeIds
}

因此,如果我自己为此创建 sql,我会简单地执行以下操作(其中 in 子句包含 codeIds 参数中的所有值):

So if I were creating the sql for this myself, I would simply do something like the following (where the in clause contains all the values in the codeIds argument):

Select CodeId, Description FROM CodeTable WHERE CodeId IN ('1a','2b','3')

在 Linq to Sql 中,我似乎找不到IN"子句的等价物.到目前为止我发现的最好的(不起作用)是:

In Linq to Sql I can't seem to find the equivalent of the "IN" clause. The best I've found so far (which doesn't work) is:

 var foo = from codeData in channel.AsQueryable<CodeData>()
           where codeData.CodeId == "1" || codeData.CodeId == "2"
           select codeData;

问题是,我无法为 linq to sql 动态生成OR"子句列表,因为它们是在编译时设置的.

The problem being, that I can't dynamically generate a list of "OR" clauses for linq to sql, because they are set at compile time.

如何使用 Linq to Sql 完成检查列是否位于动态值列表中的 where 子句?

How does one accomplish a where clause that checks a column is in a dynamic list of values using Linq to Sql?

推荐答案

使用

where list.Contains(item.Property)

或者在您的情况下:

var foo = from codeData in channel.AsQueryable<CodeData>()
          where codeIDs.Contains(codeData.CodeId)
          select codeData;

但你也可以用点表示法来做:

But you might as well do that in dot notation:

var foo = channel.AsQueryable<CodeData>()
                 .Where(codeData => codeIDs.Contains(codeData.CodeId));

这篇关于Linq to SQL 如何做“where [column] in (list of values)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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