Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: enter image description here

And here's it when I try to access that count of 2: enter image description here

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.

like image 346
Novastorm Avatar asked Oct 14 '25 21:10

Novastorm


2 Answers

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)
like image 57
MarcinJuraszek Avatar answered Oct 17 '25 12:10

MarcinJuraszek


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);
like image 38
Manish Jain Avatar answered Oct 17 '25 12:10

Manish Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!