Reputation: 700
Is there an equivalent of a SQL IN statement in LINQ to objects?
Upvotes: 5
Views: 7042
Reputation: 10115
I will go for Inner Join in this context. If I would have used contains
, it would iterate 6 times despite if the fact that there are just two matches. I just want to emphasize here that I will go for Joins instead of IN predicate.
var desiredNames = new[] { "Pankaj" };
var people = new[]
{
new { FirstName="Pankaj", Surname="Garg" },
new { FirstName="Marc", Surname="Gravell" },
new { FirstName="Jeff", Surname="Atwood" }
};
var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered select p.FirstName).ToList();
Upvotes: 0
Reputation: 1504122
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.)
Upvotes: 16