In a statement for LINQ to objects

Is there an equivalent SQL IN statement in LINQ for objects?

+5
source share
2 answers

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 this is not very efficient. You will be better off connecting:

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

(This can still be done with dotted notation, of course, but it's ultimately a bit messier.)

+16
source

I will go for Inner Join in this context. If I used contains, it would repeat 6 times, despite the fact that there are only two matches. I just want to emphasize here that I will go for Joins instead of the 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();
0

All Articles