简体   繁体   English

在使用闭包的LINQ语句中,是否可以在闭包中指定where子句?

[英]In a LINQ statement using closures, is it possible to specify a where clause within a closure?

Here is the problem I am attempting to solve. 这是我试图解决的问题。 I have 3 database tables - Sales, Customer, and Time. 我有3个数据库表 - 销售,客户和时间。 One sales record links to exactly one customer record, and one time record. 一个销售记录仅链接到一个客户记录和一个时间记录。 I want to, for the year 1996 only, look at the total sales by region (a customer is tied to a specific region), for the following further divisions: by holidays, non-holidays, weekdays, and weekends. 我想仅在1996年,根据地区(客户与特定地区相关联)的总销售情况来看待下列其他部门:假期,非假期,工作​​日和周末。 Here is the query I have so far roughly, with what I am trying to add in 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 would need to be able to, within each closure, further limit the results. 为此,我需要能够在每个闭包内进一步限制结果。 Is this possible? 这可能吗? Do I need to restructure the query? 我需要重新构建查询吗? I could of course accomplish this by breaking it apart into 4 separate queries, but it would be really nice to do it in one. 我当然可以通过将它分成4个单独的查询来实现这一点,但是在一个查询中完成它会非常好。

Thanks. 谢谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM