C# Linq to SQL:WHERE IN 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18235409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq to SQL: WHERE IN statement
提问by Clarice Bouwer
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')
Based on the above (hypothetical) SQL schema and data, I want to use Linq to SQL to get all results where the name is invalues of an array.
基于上述(假设的)SQL 模式和数据,我想使用 Linq to SQL 来获取名称在数组值中的所有结果。
string[] names = {"John", "Cassandra", "Sarah"};
var results = (from n in db.Names
where n.Name **in names**
select n).ToList();
The results should include John
and Sarah
. With that information I am then able to add the entries that need to be added, in this case Cassandra
.
结果应包括John
和Sarah
。有了这些信息,我就可以添加需要添加的条目,在这种情况下Cassandra
。
I don't want to load all the Names because the list can get exceptionally long.
我不想加载所有名称,因为列表可能会变得异常长。
采纳答案by jmoerdyk
You can use names.Contains()
:
您可以使用names.Contains()
:
string[] names = {"John", "Cassandra", "Sarah"};
var results = (from n in db.Names
where names.Contains(n.Name)
select n).ToList();
回答by King King
var results = (from n in db.Names
where names.Any(x=>x == n.Name)
select n).ToList();
回答by Michael Goldshteyn
You can use the Contains
extension method:
您可以使用Contains
扩展方法:
var results = (from n in db.Names
where names.Contains(n.Name)
select n).ToList();