【问题标题】:Get the count of values from a dictionary C#从字典 C# 中获取值的计数
【发布时间】:2016-11-25 05:16:10
【问题描述】:

我有一个Dictionary,它有一个 ID 作为键,一个列表作为值。我想知道列表中有多少列表。当我在调试时查询它时,这似乎给出了正确的值,但是当我尝试访问该数据时,它只给出 1 而不是 2 的计数。我确定这是我缺少的东西,但我不能放我的手指在它上面。

这是我通过调试检查时的计数:

当我尝试访问 2 时,它是这样的:

整个方法是:

public static List<string> getStatisticsCSVHeaders(List<Items> itemList, Dictionary<int, List<List<Statistic>>> availableStats)
{
    List<string> topRow = new List<string>();

    for (int i = 0; i < availableStats.Values.Count; i++)
    {
        topRow.Add("Phase " + (i+1));
        for (int k = 0; k < itemList.Count; k++)
            topRow.Add(getMetricHeader(itemList[k], true));
    }

    return topRow;
}

我想将列表中的列表数作为i &lt; availableStats.Values.Count 行的计数器。

编辑: 我应该提到我已经尝试过availableStats.Values[0].Count,但这不会编译。

【问题讨论】:

  • 你试过foreach(var list in YourDictionary.Value) { // .. }
  • 为什么不可用Stats.Count()?
  • @Prashant 或者availableStats.Value.Count()?
  • 字典上没有 Value.Count()。

标签: c# debugging for-loop dictionary


【解决方案1】:

调试器显示您的字典中有一个项目,该项目是一个包含 2 个元素的列表。因为您的代码正在计算您得到 1 的字典中的项目数。

要获取该字典中所有列表中所有项目的数量,请尝试 LINQ 和 Sum

availableStats.Values.Sum(x => x.Count)

【讨论】:

  • 非常感谢!这正是我所追求的 :) 如果时间允许,我会将其添加为已接受的答案。
【解决方案2】:

在您的问题中,因为 value 包含一个列表,所以它可能包含一个 null 值,因此有必要对值进行 null 检查,否则您可能会在 LINQ 查询中出现错误。

var totalCount = availableStats.Values.Sum(x => x==null? 0 : x.Count);

还有一种方法可以获得相同的结果,如下所示:

var totalCount = availableStats.Sum(x => x.Value==null? 0 : x.Value.Count);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多