C# GroupBy 并计算 List 中的唯一元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10812629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:22:09  来源:igfitidea点击:

GroupBy and count the unique elements in a List

c#.net

提问by Jason94

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 :(

会导致 Foo1: 2, Foo2: 3, Foo3: 1. 我试过使用 Linq 但列表中有一个 GroupBy 可能会起作用,但我搞砸了,无法弄清楚用途:(

采纳答案by Serj-Tm

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

回答by Royi Namir

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

回答by HW90

   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::

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


    }

Hereyou can find a very good example

在这里你可以找到一个很好的例子

回答by Igor Gorjanc

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

一个好的解决方案可在http://msdn.microsoft.com/en-us/library/vstudio/bb534304(v=vs.100).aspx这组由关键数据; 每个键都有自己的数据列表,您可以对其进行迭代。