2012-05-30 41 views
18

Sadece dizeleri içeren bir listem var. Yapmayı sevdiğim şey gruptur ve bir sayı döndürür. ÖrneğinGroupBy ve bir listedeki benzersiz öğeleri sayın

:

Foo1 
Foo2 
Foo3 
Foo1 
Foo2 
Foo2 

foo1 neden misiniz: 2, foo2: 3, Foo3: ama 1. Linq ile denedim ama liste hile yapabilir bir GroupBy vardır bunu haberci Eğer kontrol edebilirsiniz böylece kullanımını :(

cevap

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

Harika, teşekkürler! – 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() 
    }; 

NorthWind veritabanı ile çalışan bir örnek bilemiyorum, yukarı ::

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>"); 


    } 
çok iyi bir örnek bulmak için Here

İlgili konular