本文介绍了GROUPBY和计数在列表中独特的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有了只包含字符串的列表。我很想做的是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()});
 

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

这篇关于GROUPBY和计数在列表中独特的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 14:01