views:

1127

answers:

1

Is there an equivalent of a SQL IN statement in LINQ to objects?

+3  A: 

Yes - Contains.

var desiredNames = new[] { "Jon", "Marc" };

var people = new[]
{
    new { FirstName="Jon", Surname="Skeet" },
    new { FirstName="Marc", Surname="Gravell" },
    new { FirstName="Jeff", Surname="Atwood" }
};

var matches = people.Where(person => desiredNames.Contains(person.FirstName));

foreach (var person in matches)
{
    Console.WriteLine(person);
}

(In LINQ to SQL this ends up as an "IN" query.)

Note that in LINQ to Objects the above isn't really very efficient. You'd be better off with a join:

var matches = from person in people
                        join name in desiredNames on person.FirstName equals name
                        select person;

(This could still be done with dot notation of course, but it ends up being somewhat messier.)

Jon Skeet
Thank you! Your reputation precedes you ;-)
John Paul Jones