I currently have the following logic that builds a list of 4 integers, where each integer represents a sum of all votes for a certain item ID (1, 2, 3 or 4):
List<int> totals = new List<int>();
using (RepositoryEntities entityContext = new RepositoryEntities())
{
totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 1));
totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 2));
totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 3));
totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 4));
}
This works very well, but I'm questioning the efficiency of such querying, because this seems to actually generate and execute 4 separate queries. Ideally I'd want to have a single, efficient query that returns me the 4 sums.
Any ideas?
Thanks in advance.
-
might want to look here msdn.microsoft.com/en-us/vcsharp/aa336747#countGroupedConrad Frix– Conrad Frix2011年04月08日 21:13:56 +00:00Commented Apr 8, 2011 at 21:13
2 Answers 2
You could wrap your logic into one query
totals.AddRange(entityContext.ItemVotes
.Where(iv => iv.Vote >= 1 && iv.Vote <= 4)
.GroupBy(iv => iv.Vote)
.OrderBy(grp => grp.Key)
.Select(grp => grp.Count());
(This code is untested and could be way off base but just throwing out an idea)
3 Comments
in LINQ the .Count() method forces execution of a query. If you need 4 different totals there is no other way to produce that in one statement.
Comments
Explore related questions
See similar questions with these tags.