Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<int> to a Dictionary<int,int> using LINQ

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

like image 434
Setyo N Avatar asked Dec 09 '22 06:12

Setyo N


1 Answers

var result = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
like image 104
Sergey Berezovskiy Avatar answered Dec 11 '22 06:12

Sergey Berezovskiy