我有以下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();
请注意,即使具有类似where子句的两个查询也使用不同的值(例如group_period.year
和period.playyear
)
答案 0 :(得分:2)
如果这两个查询执行不同的操作,您可以将它们分开。它更具可读性。
你可以做些什么来改进,就是将这两个在数据库中作为1个查询执行。
您需要做的就是删除ToList()
:
您还可以将第二个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));