【问题标题】:Using GroupBy in LINQ [duplicate]在 LINQ 中使用 GroupBy [重复]
【发布时间】:2017-07-05 10:43:03
【问题描述】:

我有一个数据库表,其中包含每个 SMS 客户发送的条目。它看起来像这样:

CustomerId  SentBy  SentTo SentDate

我想使用 LINQ(最好是流畅的语法)创建一个报告,列出每位客户发送的 SMS 消息的总量

var smses = smsTable.GroupBy(x => x.CustomerId);

不过,我不太确定如何遍历结果。我想要以下输出:

CustomerId  SmsCount
----------------------
1234        1756
100         333

如果有任何帮助,我将不胜感激!

【问题讨论】:

    标签: c# linq .net-core


    【解决方案1】:

    根据MSDN,GroupBy返回IEnumerable<IGrouping<TKey, TElement>>,每个IGrouping对象包含一个 TElement 类型的对象和一个键的集合。

    这意味着您可以获得分组项的值将等于Key,并且每个键将与一个集合相关联。在您的情况下,您必须获取每个组中的密钥和项目计数。为此,可以使用以下代码。

    var smses = smsTable.GroupBy(x => x.CustomerId)
                        .Select(y => new 
                                     { 
                                        CustomerId = y.Key,
                                        smsCount = y.Count()
                                     });
    

    【讨论】:

    • 谢谢,工作就像一个魅力! :)
    【解决方案2】:

    尝试这样做:

    var smses = smsTable.GroupBy(x => x.CustomerId).Select(group =>
                             new
                             {
                                 CustomerId = group.Key,
                                 SmsCount = group.Count()
                             });
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多