简体   繁体   English

将两个linq查询联接到单个查询

[英]joining two linq queries to a single query

I have the following linq queries.. what is the best way to join both of them to a single query. 我有以下linq查询..什么是将它们都连接到单个查询的最佳方法。

List<string> consumerids = plays.Where(w => w.playyear == group_period.year 
                                         && w.playmonth == group_period.month 
                                         && w.sixteentile == group_period.group)
                                .Select(c => c.consumerid)
                                .ToList();


int groupcount = plays.Where(w => w.playyear == period.playyear 
                               && w.playmonth == period.playmonth 
                               && w.sixteentile == group 
                               && consumerids.Any(x => x == w.consumerid))
                      .Count();

Please note that the two queries even though have a similar where clause use different values in them (eg. group_period.year and period.playyear ) 请注意,即使两个查询具有相似的where子句,在其中使用的值也不同(例如group_period.yearperiod.playyear )。

If these 2 queries do different things, you can keep them separate. 如果这两个查询执行不同的操作,则可以将它们分开。 It is more readable that way. 这样更易读。

What you can do to improve is make these two be executed as 1 query in the database. 您可以做的是使这两个作为数据库中的1个查询执行。

All you need to do is remove the ToList() : 您需要做的就是删除ToList()

You can also have the predicate of the second Where as the predicate of the Count 您还可以将第二个Where的谓词作为Count的谓词

var consumerids = plays.Where(w => w.playyear == group_period.year &&
                                   w.playmonth == group_period.month &&
                                   w.sixteentile == group_period.group)
                       .Select(c => c.consumerid);

int groupcount = plays.Count(w => w.playyear == period.playyear &&
                                  w.playmonth == period.playmonth &&
                                  w.sixteentile == group &&
                                  consumerids.Any(x => x == w.consumerid));

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

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