20

I have a list that contains only strings. What I would love to do is group by and return a count.

For instance:

Foo1
Foo2
Foo3
Foo1
Foo2 
Foo2

Would result in Foo1: 2, Foo2: 3, Foo3: 1. I've tried with Linq but the list has a GroupBy that might do the trick but i messed it up, can't figure the use :(

mihai
  • 4,592
  • 3
  • 29
  • 42
Jason94
  • 13,320
  • 37
  • 106
  • 184

4 Answers4

36
var list = new List<string> { "Foo1", "Foo2", "Foo3", "Foo2", "Foo3", "Foo3", "Foo1", "Foo1" };

var grouped = list
    .GroupBy(s => s)
    .Select(group => new { Word = group.Key, Count = group.Count() });
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
Serj-Tm
  • 16,581
  • 4
  • 54
  • 61
5
 var items= myList
    .GroupBy(g => g)
    .Select(t => new {count= t.Count(), key= t.Key });

 foreach (var group in items)
     Console.WriteLine ( group.key + " " + group.count);
mihai
  • 4,592
  • 3
  • 29
  • 42
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
1
   var grouped =  select new
     {
         Foo= grp.Key,
         Bar= grp.Select(x => x.SomeField).Distinct().Count()
     };

a working example with the NorthWind database so that you can check::

    NWindCustomersDataContext dc = new NWindCustomersDataContext();


    var query = (from c in dc.Customers
                 join o in dc.Orders on c.CustomerID equals o.CustomerID
                 group o by c.CustomerID into g
                 select new
                 {
                     CustomerID = g.Key,
                     Company = (from cust in dc.Customers
                               where cust.CustomerID == g.Key
                               select cust).ToList(),
                     Count = g.Select(x => x.OrderID).Distinct().Count()
                 }).OrderByDescending(y => y.Count);




    foreach (var item in query)
    {
        Response.Write("CustomerID: " + item.CustomerID + "</br>" + "CompanyName: " + item.Company[0].CompanyName.ToString() + "</br>");


    }

Here you can find a very good example

Community
  • 1
  • 1
HW90
  • 1,953
  • 2
  • 21
  • 45
0

A good solution is available on http://msdn.microsoft.com/en-us/library/vstudio/bb534304(v=vs.100).aspx It groups data by key; each key has it's own list of data you can iterate over it.

Igor Gorjanc
  • 535
  • 4
  • 17