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

uza*_*y95 10 c# linq dictionary

我想获得List以下s中项目的总数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);
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 23

我相信这会让你有效而清晰地获得你想要的数量.在引擎盖下,它必须遍历列表,但为了获得总计数,没有办法避免这种情况.

var i = dd.Values.Sum(x => x.Count);
Run Code Online (Sandbox Code Playgroud)