GROUPBY和计数在列表中独特的元素元素、独特、列表中、GROUPBY

2023-09-03 00:23:34 作者:转身、你已卟在

我拥有了只包含字符串的列表。我很想做的是GROUP BY和返回一个计数。

例如:

  Foo1
foo2的
Foo3
Foo1
foo2的
foo2的
 

将导致Foo1:2和Foo2:3,Foo3:1。我尝试过使用LINQ,但列表中有可能做的伎俩,但我把事情搞糟了,想不通使用GROUPBY:(

解决方案

  VAR列表=新的名单,其中,串> {Foo1,foo2的,Foo3,foo2的,Foo3,Foo3,Foo1,Foo1};

VAR分组=列表
    .GroupBy(S =&GT氏)
    。选择(组=>新建{字= group.Key,计数= group.Count()});
 

SPL 简化 SQL 案例详解 多层固定分组

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

解决方案

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

 
精彩推荐
图片推荐