计算列表中出现次数的方法 [英] A method to count occurrences in a list
问题描述
有一个简单的方法来计算一个列表中的所有元素出现在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
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屋!