LINQ中的计数和最大列分组依据

时间:2018-12-11 13:51:08

标签: c# linq

我有模特

public class Rate
{
    public int Nr{ get; set; }
    public string Rate{ get; set; }
    public int Order{ get; set; }
}

和这样的RateList = List<Rate>

Nr  |  Rate |  Order
123 |   A   |    2
425 |   A+  |    1
454 |   B   |    4
656 |   B+  |    3
465 |   A   |    2
765 |   B   |    4

请注意,订单始终与费率(A+ = 1, A = 2, B+ = 3, B = 4, C+ = 5 ...)相匹配 我想计算发生率多少次并按订单显示订单

结果应该像这样

  Rate | Count | Order
   A+  |   1   |  1
   A   |   2   |  2
   B+  |   1   |  3
   B   |   2   |  4

或不包含列Order

  Rate | Count 
   A+  |   1   
   A   |   2   
   B+  |   1   
   B   |   2 

在SQL中,如果我在表Tab中有上面的列表,则可以这样做

SELECT Rate, COUNT(Rate), Max(Order) from Tab group by Rate

但是在LINQ中吗?

我正在尝试类似的事情

    var rating= RateList.Distinct().GroupBy(x => x.Rate)
.Select(x => new { Rate = x.Key, RateCount = x.Count() })
.OrderBy(x => x.Order);

但是没用。 谢谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您的SQL查询等同于:

var rating = rateList.GroupBy(x => x.Rate)
                     .Select(x => new { 
                              Rate = x.Key, 
                              RateCount = x.Count(e => e != null),
                              Max = x.Max(g => g.Order) 
                       });