C# 将两个linq查询连接到单个查询
我有以下linq问题。。将两者连接到单个查询的最佳方式是什么C# 将两个linq查询连接到单个查询,c#,linq,C#,Linq,我有以下linq问题。。将两者连接到单个查询的最佳方式是什么 List<string> consumerids = plays.Where(w => w.playyear == group_period.year && w.playmonth == group_period.month &
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();
List consumerids=plays.Where(w=>w.playyear==group\u period.year
&&w.playmonth==组周期月份
&&w.Sixtentile==组(周期组)
.选择(c=>c.consumerid)
.ToList();
int groupcount=plays.Where(w=>w.playyear==period.playyear
&&w.playmonth==期间.playmonth
&&w.Sixtentile==组
&&consumerids.Any(x=>x==w.consumerid))
.Count();
请注意,尽管这两个查询具有相似的where子句,但它们使用了不同的值(例如
group\u period.year
和period.playyear
)如果这两个查询执行不同的操作,您可以将它们分开。这样更容易阅读
可以改进的是,将这两个查询作为数据库中的一个查询执行
您只需删除ToList()
:
您还可以使用第二个的谓词,其中
作为计数的谓词
为什么需要将它们作为单个查询?这可能会损害可读性。另外,这样的查询结果应该是什么?为什么不直接计算
消费者的数量呢?
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));