简体   繁体   中英

Get the count of values from a dictionary C#

I have a Dictionary which has an ID as the key and a list of lists as the value. I would like to get the count of how many lists are inside the list. This appears to give the correct value when I query it whilst debugging but when I go to try and access that data it only gives a count of 1 rather than 2. I'm sure it's something I'm missing but I can't put my finger on it.

Here's the count when I check it through debugging: 在此处输入图片说明

And here's it when I try to access that count of 2: 在此处输入图片说明

The whole method is:

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'd like to have the number of lists inside my list as the counter for the line i < availableStats.Values.Count .

EDIT: I should mention I've tried availableStats.Values[0].Count but this won't compile.

Debugger shows that you have a single item in your dictionary, and that item is a list with 2 elements. Because your code is taking the count of item in the dictionary you're getting 1.

To get the number of all the items in all the lists in that dictionary, try LINQ and Sum :

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

In your question, because value contains a list, so it is possible that it may contain a null value, so it is necessary to do a null check for values otherwise you can get an error inside your LINQ query.

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

There is one more way to get same result as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM