GroupBy and count the unique elements in a List

后端 未结 4 1637
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 09:56

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


        
相关标签:
4条回答
  • 2020-12-17 10:09
       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

    0 讨论(0)
  • 2020-12-17 10:11

    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.

    0 讨论(0)
  • 2020-12-17 10:17
    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 讨论(0)
  • 2020-12-17 10:25
     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);
    
    0 讨论(0)
提交回复
热议问题