group by in linq
程序员文章站
2022-07-04 10:23:52
...
想实现一个从数据库根据某个字段和一定条件查询记录条数的方法:
1.先取字段的可能情况,再通过循环去数据库查询:
var conversations = Repository.FindAll().AsExpandable().Where(t => t.IsHidden == false && t.Status != ConversationStatus.Closed && t.IsDeleted == false && t.DepartmentId == departmentId);
如果数据太多,这种方法会比较消耗性能
2.通过linq的group by 方法来将查询结果:
var conversations = Repository.FindAll().AsExpandable().Where(t => t.IsHidden == false && t.Status != ConversationStatus.Closed && t.IsDeleted == false);
var groupConversations = from p in conversations
group p by p.DepartmentId into g
select g;
两个对比,时间复杂度虽然一样,但是第二种方法做的循环会减少,在字段可取的情况下会比较理想。
下一篇: group by 和 order by