Say I have the following list:
List<int> list = new List<int>() { 5, 5, 6, 6, 6, 7, 7, 7, 7 };
How could I convert the list to a Dictionary where the value is the count of each distinct number in the list by using LINQ? For example, the above list should be converted to a dictionary with the elements:
key -> value
5 -> 2
6 -> 3
7 -> 4
var result = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With