Here is a quick C# tip of counting up values of a Dictionary<TKey, TValue> where the values contains a List<T> using Linq.
Lets say you have a Dictionary that contains Dictionary<string, List<Guid>> and you wish to find out how many items of Guid you have.
You can easily do it by the Sum Linq aggregate operations
1 |
int sum = dict.Sum(x => x.Value.Count); |
This will tell you the amount of items you have in all the list.
And if you wish to just find out if there are any items in the list, rather than counting. For example you need to enable or disable a button on a UI, one can use the Linq Any quantifiers, it would be more efficient than the Sum Aggregate operator.
1 2 3 |
var hasItems = dict.Any(x => x.Value.Any()); MyButton.Enabled = hasItems; |
Leave A Comment