我目前有以下逻辑来构建 4 个整数的列表,其中每个整数代表某个项目 ID(1、2、3 或 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));
}
这工作得很好,但我质疑这种查询的效率,因为这似乎实际上生成并执行了 4 个单独的查询。理想情况下,我想要一个有效的查询,返回 4 个总和。
有什么想法吗?
提前致谢。
最佳答案
您可以将逻辑包装到一个查询中
totals.AddRange(entityContext.ItemVotes
.Where(iv => iv.Vote >= 1 && iv.Vote <= 4)
.GroupBy(iv => iv.Vote)
.OrderBy(grp => grp.Key)
.Select(grp => grp.Count());
(此代码未经测试,可能偏离基础,但只是抛出一个想法)
关于c# - LINQ to Entity 查询优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5600792/