Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In statement for LINQ to objects

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

like image 492
John Paul Jones Avatar asked Jan 08 '09 10:01

John Paul Jones


People also ask

What is LINQ to object?

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.

What a LINQ query returns in LINQ to object?

Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().


1 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 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.)

like image 106
Jon Skeet Avatar answered Sep 25 '22 20:09

Jon Skeet