I want to get the total number of items in the List
s in the following Dictionary
:
我想在以下词典中获取列表中的项目总数:
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);
5 个解决方案
#1
I believe this will get you the count you want efficiently and clearly. Under the hood it has to iterate through the lists, but to get a total count, there is no way to avoid this.
我相信这会让你有效而清晰地获得你想要的数量。在引擎盖下,它必须遍历列表,但为了获得总计数,没有办法避免这种情况。
var i = dd.Values.Sum(x => x.Count);
#2
var i = dd.Values.SelectMany(v => v).Count();
#3
Total count of all list items:
所有列表项的总数:
dd.SelectMany(i => i.Value).Count();
List
containing individual list counts:
包含单个列表计数的列表:
dd.Select(i => i.Value.Count).ToList()
#4
How about this?
这个怎么样?
var l = dd.Select(i => new {i, i.Value.Count});
#5
var total = dictionary.Sum(x => x.Value.Count());
var total = dictionary.Sum(x => x.Value.Count());
#1
I believe this will get you the count you want efficiently and clearly. Under the hood it has to iterate through the lists, but to get a total count, there is no way to avoid this.
我相信这会让你有效而清晰地获得你想要的数量。在引擎盖下,它必须遍历列表,但为了获得总计数,没有办法避免这种情况。
var i = dd.Values.Sum(x => x.Count);
#2
var i = dd.Values.SelectMany(v => v).Count();
#3
Total count of all list items:
所有列表项的总数:
dd.SelectMany(i => i.Value).Count();
List
containing individual list counts:
包含单个列表计数的列表:
dd.Select(i => i.Value.Count).ToList()
#4
How about this?
这个怎么样?
var l = dd.Select(i => new {i, i.Value.Count});
#5
var total = dictionary.Sum(x => x.Value.Count());
var total = dictionary.Sum(x => x.Value.Count());