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();
结果应包括John
和Sarah
。有了这些信息,我就可以添加需要添加的条目,在本例中为Cassandra
。
我不想加载所有名称,因为列表可能会异常长。
答案 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();