Group by and count in List

Here's an example of all sorts of loops and checks:

var items = new Dictionary<int,int>();
foreach(var number in numbers)
{
   if(items.ContainsKey(number))
      items[number]++;
   else
      items.Add(number, 1);
}

Just for reference anyway. I prefer the LINQ approach, but it's not really as bad of a problem as you may have believed.


Use GroupBy and Count:

var numberGroups = numbers.GroupBy(i => i);
foreach(var grp in numberGroups)
{
    var number = grp.Key;
    var total  = grp.Count();
}

Here's another example which uses an anonymous type to store some informations. It also creates an array since it seems to be the desired result:

var numberGroups = numbers.GroupBy(i => i)
                   .Select(grp => new{
                       number  = grp.Key,
                       total   = grp.Count(),
                       average = grp.Average(),
                       minimum = grp.Min(),
                       maximum = grp.Max()
                   })
                   .ToArray();

foreach (var numInfo in numberGroups)
{
    var number = numInfo.number;
    // ...
    var maximum = numInfo.maximum;
}

Use this

var result = numbers.GroupBy(n => n)
                    .Select(c => new { Key = c.Key, total = c.Count() });

My solution:

var result = from i in n 
group i by i into g
select new {g.Key, Count= g.Count()};

Tags:

C#