一种计算列表中出现次数的方法

Non*_*biz 45 c# list count match .net-3.5

有没有一种简单的方法可以将列表中所有元素的出现次数计入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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

JP *_*oto 79

这样的事情怎么样......

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() );
}
Run Code Online (Sandbox Code Playgroud)

根据评论编辑:我会尽力做到这一点.:)

在我的例子中,这是Func<int, TKey>因为我的列表是整数.所以,我告诉GroupBy如何分组我的项目.Func接受一个int并返回我的分组键.在这种情况下,我将得到一个IGrouping<int,int>(由int键入的一组int).i => i.ToString()例如,如果我将其更改为(),我会用字符串键入我的分组.您可以想象一个不那么简单的例子,而不是用"1","2","3"来键入......也许我会创建一个返回"one","two","three"的函数作为我的关键...

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

所以,这是一个Func,它会接受一个int并返回一个字符串,就像......

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 
Run Code Online (Sandbox Code Playgroud)

但是,由于最初的问题需要知道原始列表值和它的计数,我只是使用一个整数来键入我的整数分组以使我的示例更简单.


Sta*_* R. 16

你可以做一些这样的事情从一系列事物中算起来.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();
Run Code Online (Sandbox Code Playgroud)

计算单个元素

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();
Run Code Online (Sandbox Code Playgroud)


Ste*_*ham 14

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    
Run Code Online (Sandbox Code Playgroud)

这取自linqpad中的一个示例