如何在不使用foreach的情况下获取字典中嵌套列表计数的总和?

13

我想获取以下DictionaryList中的所有项数的总和:

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吗? - Timothy Carter
我想要计算字典列表中每个项目的总数。 - uzay95
5个回答

25

我相信这将有效而清晰地为您获取所需的计数。在内部,它必须遍历列表,但要获得总计数,没有办法避免这种情况。

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

2
var i = dd.Values.SelectMany(v => v).Count();

2

所有列表项的总数:

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

List 包含各个列表的计数:

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

使用SelectMany的好答案。 - uzay95

0

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

变量total等于字典中所有值的数量之和。


0

这个怎么样?

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

哦,没看到最后一条评论... 哎,算了。 - BigBlondeViking

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接