一种计算列表中出现次数的方法 [英] 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#?
像这样:
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]);
}
}
推荐答案
这样的事情怎么样...
How about something like this ...
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
因为我的列表是整数.所以,我告诉 GroupBy 如何对我的项目进行分组.Func 接受一个 int 并返回我的分组的键.在这种情况下,我将得到一个 IGrouping
(由 int 键控的一组 int).例如,如果我将其更改为 (i => i.ToString()
),我将按字符串键控我的分组.你可以想象一个比键控1"、2"、3"更简单的例子......也许我制作了一个返回一"、二"、三"作为我的键的函数......
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.
}
所以,这是一个接受 int 并返回一个字符串的 Func,就像 ...
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屋!