19
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 in values of an array.

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.

I don't want to load all the Names because the list can get exceptionally long.

4

3 回答 3

30

您可以使用names.Contains()

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

var results = (from n in db.Names
               where names.Contains(n.Name)
               select n).ToList();
于 2013-08-14T15:12:34.377 回答
5

您可以使用Contains扩展方法:

var results = (from n in db.Names
               where names.Contains(n.Name)
               select n).ToList();
于 2013-08-14T15:12:24.377 回答
3
var results = (from n in db.Names
               where names.Any(x=>x == n.Name)
               select n).ToList();
于 2013-08-14T15:10:37.650 回答