我如何避免在此LINQ中重复语句的某些部分

时间:2018-08-22 02:09:56

标签: linq

User.Where(u => new int[]{1,2}.Contains(u.Org_id)).GroupBy(u => u.Org_id)
.Select(g => new {GroupId = g.Key, UserCount =  g.Where(gu => gu.Role == 1).Count(), Users = g.Where(gu => gu.Role == 1)})
.Take(500)

语句的g.Where(gu => gu.Role == 1)部分已重复,如何避免重复?

2 个答案:

答案 0 :(得分:1)

您可以尝试更新委托

例如

User.Where(u => new int[]{1,2}.Contains(u.Org_id))
.GroupBy(u => u.Org_id) 
.Select(g => {
    var items = g.Where(gu => gu.Role == 1);
    return new {GroupId = g.Key, UserCount =  items.Count(), Users = items };
})
.Take(500);

答案 1 :(得分:0)

选项1:不存储计数(这是多余的):

User.Where(u => new int[]{1,2}.Contains(u.Org_id))
    .GroupBy(u => u.Org_id)
    .Select(g => new {GroupId = g.Key, Users = g.Where(gu => gu.Role == 1).ToList()})
    .Take(500)

选项2:投影两次:

User.Where(u => new int[]{1,2}.Contains(u.Org_id))
    .GroupBy(u => u.Org_id)
    .Select(g => new {GroupId = g.Key, Users = g.Where(gu => gu.Role == 1).ToList()})
    .Select(x => new {GroupId = x.GroupId, Users = x.Users, UserCount = x.Users.Count})
    .Take(500)