Reputation: 2354
I have the following linq queries.. what is the best way to join both of them to a single query.
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
)
Upvotes: 1
Views: 86
Reputation: 37299
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.
All you need to do is remove the ToList()
:
You can also have the predicate of the second Where
as the predicate of the 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));
Upvotes: 2