2012-05-30 25 views
18

Ho una lista che contiene solo stringhe. Quello che mi piacerebbe fare è raggruppare e restituire un conteggio.Raggruppa e conta gli elementi univoci in un elenco

Per esempio:

Foo1 
Foo2 
Foo3 
Foo1 
Foo2 
Foo2 

comporterebbe foo1: 2, foo2: 3, Foo3: 1. Ho provato con Linq ma la lista ha un GroupBy che potrebbe fare il trucco, ma ho messo esso up, non riesco a capire l'uso :(

risposta

34
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() }); 
+0

Fantastico, grazie! – Jason94

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); 
1
var grouped = select new 
    { 
     Foo= grp.Key, 
     Bar= grp.Select(x => x.SomeField).Distinct().Count() 
    }; 

un esempio di lavoro con il database Northwind in modo da poter controllare ::

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 è possibile trovare un ottimo esempio

Problemi correlati