计算列表中出现次数的方法 [英] A method to count occurrences in a list

查看:192
本文介绍了计算列表中出现次数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法来计算一个列表中的所有元素出现在C#中的同一个列表中的出现次数?

Is there a simple way to count the number of occurrences of all elements of a list into that same list in C#?

使用System:

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

string Occur;
List<string> Words = new List<string>();
List<string> Occurrences = new List<string>();

// ~170 elements added. . . 

for (int i = 0;i<Words.Count;i++){
    Words = Words.Distinct().ToList();
    for (int ii = 0;ii<Words.Count;ii++){Occur = new Regex(Words[ii]).Matches(Words[]).Count;}
         Occurrences.Add (Occur);
         Console.Write("{0} ({1}), ", Words[i], Occurrences[i]);
    }
}


推荐答案

关于这样的...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

编辑每个注释:我会尝试做这个正义。 :)

Edit per comment: I will try and do this justice. :)

在我的例子中,它是一个 Func ,因为我的列表是ints。所以,我告诉GroupBy如何分组我的项目。 Func接受一个int并返回我的分组的键。在这种情况下,我会得到一个 IGrouping< int,int> (由int键入的int的分组)。例如,如果我将它改为( i => i.ToString()),我将通过字符串键入我的分组。你可以想象一个不太平凡的例子,而不是键入1,2,3...也许我做一个函数,返回一,两个,三 / p>

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

一个Func,它将接受一个int并返回一个字符串,就像...

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

但是,由于原始问题要求知道原始列表值及其计数,我只是使用整数来键入我的整数分组,使我的示例更简单。

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

这篇关于计算列表中出现次数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆