Reputation: 1458
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.
Upvotes: 4
Views: 10874
Reputation: 1353
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);
Upvotes: 1
Reputation: 125630
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)
Upvotes: 7