【问题标题】:How do I get the sum of the Counts of nested Lists in a Dictionary without using foreach?如何在不使用 foreach 的情况下获得字典中嵌套列表计数的总和?
【发布时间】:2010-11-13 10:01:40
【问题描述】:

我想在下面的Dictionary中获取Lists中的项目总数:

Dictionary<int, List<string>> dd = new Dictionary<int, List<string>>() {
    {1, new List<string> {"cem"}},
    {2, new List<string> {"cem", "canan"}},
    {3, new List<string> {"canan", "cenk", "cem"}}
};

// This only returns an enumerated array.
var i = (from c in dd
         select c.Value.Count).Select(p=>p);

【问题讨论】:

  • 您想要总数吗?在示例 6 的情况下?
  • 是的。我想谈谈字典列表中每一项的计数。

标签: c# linq dictionary


【解决方案1】:

我相信这会让您高效而清晰地获得所需的计数。在引擎盖下它必须遍历列表,但要获得总计数,没有办法避免这种情况。

var i = dd.Values.Sum(x => x.Count);

【讨论】:

    【解决方案2】:
    var i = dd.Values.SelectMany(v => v).Count();
    

    【讨论】:

      【解决方案3】:

      所有列表项的总数:

      dd.SelectMany(i => i.Value).Count();
      

      List 包含单个列表计数:

      dd.Select(i => i.Value.Count).ToList()
      

      【讨论】:

      • 与 SelectMany 一起使用的好答案。
      【解决方案4】:

      这个怎么样?

      var l = dd.Select(i => new {i, i.Value.Count});
      

      【讨论】:

      • 哦,没看到最后的评论...哦,好吧
      【解决方案5】:

      var total = dictionary.Sum(x => x.Value.Count());

      【讨论】:

        猜你喜欢
        • 2010-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 2019-06-13
        • 2021-02-02
        • 1970-01-01
        相关资源
        最近更新 更多