GroupBy并计算List中的唯一元素

时间:2012-05-30 08:28:13

标签: c# .net

我有一个只包含字符串的列表。我喜欢做的是分组并返回一个计数。

例如:

Foo1
Foo2
Foo3
Foo1
Foo2 
Foo2

会导致Foo1:2,Foo2:3,Foo3:1。我已经尝试过使用Linq,但是列表中有一个GroupBy,可能会做这个伎俩但是搞砸了,无法计算使用:(< / p>

4 个答案:

答案 0 :(得分:35)

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

答案 1 :(得分: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);

答案 2 :(得分:1)

   var grouped =  select new
     {
         Foo= grp.Key,
         Bar= grp.Select(x => x.SomeField).Distinct().Count()
     };

使用NorthWind数据库的一个工作示例,以便您可以检查::

    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你可以找到一个很好的例子

答案 3 :(得分:0)

http://msdn.microsoft.com/en-us/library/vstudio/bb534304(v=vs.100).aspx提供了一个很好的解决方案 它按密钥分组数据;每个键都有自己的数据列表,你可以迭代它。