1

I have for example this list.

List<int> numbers = new List<int>() { 1, 1, 2, 2, 3, 3, 4 };

And I want to get another list with count of each distinct item in that list, so something like this 2,2,2,1. I guess it is possible to reach it by using foreach, but is it possible in easier way(LINQ maybe)? Thanks.

Martin
  • 11
  • 1
  • 2

1 Answers1

8
var counts = numbers.GroupBy(x => x)
                    .Select(g => new { Number = g.Key, Count = g.Count() })
                    .ToList();

Instead of anonymous objects, you can use a dictionary too

var counts = numbers.GroupBy(x => x)
                    .ToDictionary(x => x.Key, x => x.Count());
EZI
  • 15,209
  • 2
  • 27
  • 33