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.

3 Answers 3

30

You can use names.Contains():

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

var results = (from n in db.Names
               where names.Contains(n.Name)
               select n).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Such an obvious answer. I can't believe I never thought of it.
5

You can use the Contains extension method:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.