从GroupBy列表

时间:2017-08-01 17:56:24

标签: c# linq

型号:

public class Ticket {
    public Ticket();

    public int Id { get; set; }
    public virtual TicketUrgency TicketUrgency { get; set; }
    public int UrgencyId { get; set; }   
}

public class TicketUrgency {
    public TicketUrgency();
    [Key]
    public int Id { get; set; }
    [MaxLength(50)]
    [Required]
    public string Name { get; set; }
    public ICollection<Ticket> Tickets { get; set; }
}

我有以下linq声明:

 var model = Entities
                .Include(x => x.TicketUrgency)
                .GroupBy(x => x.UrgencyId)
                .Select(g => new {
                    id = g.Key,
                    count = g.Count(),
                    name = g.FirstOrDefault(u => u.UrgencyId == g.Key).TicketUrgency.Name
                });

我希望按EntitiesUrgencyId进行分组,然后返回密钥(UrgencyId),并计算单个组中的项目并显示紧急程度的名称。< / p>

当我运行它时,查询会挂起而没有任何异常。

4 个答案:

答案 0 :(得分:1)

很简单。试试这个:

 var model = Entities
                .Include(x => x.TicketUrgency)
                .GroupBy(x => new {UrgencyId =  x.UrgencyId ,
                          Name = x.TicketUrgency.Name})
                .Select(x=> new { UrgencyId = x.Key.UrgencyId,
                                  Name = x.Key.Name,
                                  Count = x.Count()});

答案 1 :(得分:1)

您可以按这两个属性进行分组:

var model = Entities
            .Include(x => x.TicketUrgency)
            .GroupBy(x => new{ x.UrgencyId, x.TicketUrgency.Name })
            .Select(g => new {
                id = g.Key.UrgencyId,
                count = g.Count(),
                name = g.Key.Name 
            });

另一种方式可能是,正如@ASpirin建议的那样,从TickerUrgency开始查询:

var result= TicketUrgencies.Include(t=>t.Tickets)
                           .Where(t=>t.Tickets.Any())
                           .Select(t=> new {id=t.Id,name=t.Name, count= t.Tickets.Count()})

答案 2 :(得分:1)

由于您按g进行分组,因此您知道Key的所有成员都具有与var model = Entities .Include(x => x.TicketUrgency) .GroupBy(x => x.UrgencyId) .Select(g => new { id = g.Key, name = g.First().TicketUrgency.Name count = g.Count(), }); 相同的ID,因此要获取该名称只需拉出第一个。你也知道g不是空的,因为那不会成为一个群体:

on behalf of

答案 3 :(得分:1)

通过首先检索所有TicketUrgencies并对其进行分组,这应该可行,反之亦然。

Entities.Include(e => e.Tickets)
               .GroupBy(t => t.Id)
               .Select(g => new {
                   id = g.Key,
                   name = g.FirstOrDefault().Name,
                   count = g.FirstOrDefault().Tickets.Count()
               });