Linq to SQL:WHERE IN语句

时间:2013-08-14 15:07:42

标签: c# sql linq

CREATE TABLE [MyNames]
(
    [ID] INT IDENTITY PRIMARY KEY,
    [Name] NVARCHAR(255) NULL
)

INSERT INTO [MyNames] VALUES ('John')
INSERT INTO [MyNames] VALUES ('Jane')
INSERT INTO [MyNames] VALUES ('Peter')
INSERT INTO [MyNames] VALUES ('Montgomery')
INSERT INTO [MyNames] VALUES ('Sarah')

基于上述(假设的)SQL架构和数据,我想使用Linq to SQL获取名称> 数组值的所有结果。

string[] names = {"John", "Cassandra", "Sarah"};

var results = (from n in db.Names
               where n.Name **in names**
               select n).ToList();

结果应包括JohnSarah。有了这些信息,我就可以添加需要添加的条目,在本例中为Cassandra

我不想加载所有名称,因为列表可能会异常长。

3 个答案:

答案 0 :(得分:23)

您可以使用names.Contains()

string[] names = {"John", "Cassandra", "Sarah"};

var results = (from n in db.Names
               where names.Contains(n.Name)
               select n).ToList();

答案 1 :(得分:4)

您可以使用Contains扩展名方法:

var results = (from n in db.Names
               where names.Contains(n.Name)
               select n).ToList();

答案 2 :(得分:3)

var results = (from n in db.Names
               where names.Any(x=>x == n.Name)
               select n).ToList();