LINQ: search collection in collection for one object

I am looking for a nice simple LINQ query that can get an item in a collection of a collection. Consider the following models ...

class Customer { List<Order> Orders; int ID; } class Order { int ID; } 

Suppose I have a list of clients like ...

 List<Customer> Customers; 

What I want is a single order based on the order ID (this is my known input). I can also assume that the order is unique to the customer (so there will be only one order with the identifier that I am looking for for all customers)

Is there a good LINQ query that I can use to get the order I'm looking for?

I know that I can easily do this on one list of orders, but this is a setting that I need to work with. I do not want to request more data if I already have enough memory to get what I need.

I could do this with a semi-arid cycle. Maybe I just need to do this? Maybe I'm simplifying the code too much?

+6
source share
2 answers

Oops, read the question incorrectly:

 var matchingOrders = from customer in customers from order in customer.Orders where order.ID == orderID select order; var order = matchingOrders.Single(); 

As with the earlier version of this answer, note that this will fail if there are no such matches or more than one. You can also look at SingleOrDefault , First and FirstOrDefault .

This code can also be written without query expressions using SelectMany :

 var order = customers.SelectMany(customer => customer.Orders) .Single(order => order.ID == orderID); 

Note that you do not need to use Where , and then Single - there Single overloads using the predicate (as well as for FirstOrDefault , etc.). It doesn't matter if you use a query expression form or not, I usually use query expressions rather than SelectMany , but in this case you don't need a client, so you can use SelectMany simple overloading.

+13
source

here 2 is the order identifier

  var selectedOrder = customers.SelectMany(cc => cc.Orders.Where(cc1 => cc1.ID == 2)).FirstOrDefault(); 
+2
source

Source: https://habr.com/ru/post/904092/


All Articles