问题描述
有没有一种简单的方法来计算一个列表中的所有元素中出现的次数成同一列表在C#?事情是这样的:
使用系统;
使用System.IO;
使用System.Text.RegularEx pressions;
使用System.Collections.Generic;
使用System.Linq的;
字符串发生;
名单<字符串>字=新的名单,其中,串>();
名单<字符串>出现次数=新的名单,其中,串>();
//〜170元素的加入。 。 。
的for(int i = 0; I< Words.Count;我++){
。字= Words.Distinct()了ToList();
对于(INT II = 0; II蛋白酶Words.Count;二++){=发生新的正则表达式(字[II])匹配(字[])计数;}
Occurrences.Add(发生);
Console.Write({0}({1}),字[I]中,出现次数[I]);
}
}
如何这样的事情...
VAR L1 =新的名单,其中,INT>(){1,2,3,4,5,2,2,2,4,4,4,1};
变种克= l1.GroupBy(ⅰ= I标记);
的foreach(克VAR GRP)
{
Console.WriteLine({0} {1},grp.Key,grp.Count());
}
每个注释编辑:我会尽力做到这一点正义。 :)
在我的例子,这是一个 Func键< INT,TKEY的>
,因为我的名单是整数。所以,我要告诉GROUPBY如何分组我的项目。该函数功能需要一个int和返回键为我的分组。在这种情况下,我会得到一个 IGrouping< INT,INT>
(一个int整数键控的一组)。如果我把它改为( I => i.ToString()
)为例,我会用一个字符串键控我的分组。你能想象一个没有价值的例子比1抠像,2,3...也许我做一个函数,返回一,二,三是我的钥匙...
私人字符串SampleMethod(int i)以
{
//神奇地回到一如果我== 1,二如果我== 2,等等。
}
所以,这是一个函数功能,将采取一个int,并返回一个字符串,就像...
I => //神奇地回到一如果我== 1,二如果我== 2,等等。
不过,既然叫原来的问题进行了解,原列表值,它的数量,我只是用一个整数键入我的整数分组,使我的例子简单。
Is there a simple way to count the number of occurences of all elements of a list into that same list in C#? Something like this:
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. :)
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.
}
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.
这篇关于C#的方法计算出现在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!