Csharp group by release

Hi guys, I have a question about Linq.

I am grouping the result in a zipcode client. For each zip code I want to see the number of orders and the number of equipment ordered.

So far, my code looks like this:

var statistics = from b in db.Bookings
                 from c in db.Customers
                 where b.customerID == c.id
                 group c by c.zipcode into stat
                 select new { 
                              Zipcode = stat.Key, 
                              NumberOfBookings = stat.Count() 
                            };

These code groups lead to zip codes and give me the number of orders in each zip code. How can I get the amount of equipment?

+4
source share
1 answer

Instead of using it join, as in SQL, you can (and better) use the navigation properties from your model:

var statistics = 
    from b in db.Bookings
    group b by b.Customer.zipcode into g
    select new
    { 
        Zipcode = g.Key,
        NumberOfBookings = g.Count(),
        NumberOfEquipments = g.SelectMany(b => b.Equipments).Count(),
    };

, g zipcode, SelectMany Count.

, , , Sum:

NumberOfEquipments = g.Sum(b => b.Equipments.Count())
+2

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


All Articles