Is there an equivalent of a SQL IN statement in LINQ to objects?
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>.
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.
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().
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With