Reputation: 46222
I have the following query:
DateTime cutoffDate = new DateTime(1997, 1, 1);
var orders =
from c in customers
where c.Region == "WA"
from o in c.Orders
where o.OrderDate >= cutoffDate
select new { c.CustomerID, o.OrderID };
How can this be written in Linq Lambda? BTW, is this known as a SelectMany query?
Also this can be done with a join, what is the pros and cons with doing it as shown above.
Upvotes: 4
Views: 9457
Reputation: 28718
Yes, this is a SelectMany
. You use SelectMany
to 'flatten' a nested or tiered collection (in this case, the orders are nested under customers) into a simple single-tier collection.
customers.Where(c => c.Region == "WA")
.SelectMany(c => c.Orders)
.Where(o => o.Orderdate >= cutoffDate)
.Select(x => new { x.OrderID, x.Customer.CustomerID });
If the Orders are a property of the Customer then there is no need to use a join.
Upvotes: 7