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
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
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.
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() });
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);