In a LINQ statement using closure, is it possible to specify where clause in closure?

Here is the problem I'm trying to solve. I have 3 database tables - Sales, Customer and Time. One sales record is associated with one customer record and one time record. I want, only in 1996, to look at the total sales by region (the client is tied to a certain region), for the following further divisions: on holidays, weekends, working days and days off. Here is a query that I still have rude with what I'm trying to add in the comments.

var totalSales = 
    from s in sales
    where s.Time.Year = 1996
    group s by s.Customer.Region into g
    select new { Region = g.Key, 
                Holidays = g.Sum(s => s.Total_Amount), // WHERE (s => s.Time.Holiday_flag = true)
                NonHolidays = g.Sum(s => s.Total_Amount), // WHERE (s => s.Time.Holiday_flag = false)
                Weekdays = g.Sum(s => s.Total_Amount), // WHERE (s => s.Time.Weekday_flag = true)
                Weekends = g.Sum(s => s.Total_Amount)}; // WHERE (s => s.Time.Weekday_flag = false)

To do this, I will need to be able to further limit the results within each close. Is it possible? Do I need to restructure the request? I could, of course, accomplish this by breaking it into 4 separate queries, but it would be very nice to do this in one.

Thank.

+3
source share
1 answer

Well, you could try this:

Holidays = g.Where(s => s.Time.Holiday_flag).Sum(s => s.Total_Amount),
NonHolidays = g.Where(s => !s.Time.Holiday_flag).Sum(s => s.Total_Amount),
Weekdays = g.Where(s => s.Time.Weekday_flag).Sum(s => s.Total_Amount),
Weekends = g.Where(s => !s.Time.Weekday_flag).Sum(s => s.Total_Amount)

or

Holidays = g.Sum(s => s.Time.Holiday_flag ? s.Total_Amount : 0),
// etc
+6
source

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


All Articles