2009-07-16 30 views
37

有一种简单的方法来计算列表中的所有元素出现在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]); 
    } 
} 

回答

67

如何这样的事情...根据注释

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()); 
} 

编辑:我会尝试这样做正义。 :)

在我的例子中,这是一个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. 
} 

所以,这就是,将采取一个int并返回一个字符串,就像函数求...

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

但是,因为呼吁知道原始列表值原来的问题,它的数量,我只是使用一个整数来键入我的整数分组,以使我的示例更简单。

-1

你的外循环遍历列表中的所有单词。这是不必要的,会导致你的问题。删除它,它应该正常工作。

7

你可以这样做,从一系列事情中算数。

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(); 

要计算一个单个元素

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

int count = words.Where(x => x.Equals(occur)).Count(); 
+1

+1:我花了一段时间才弄清楚,的getMethods()只是你的事情列表。 :) – 2009-07-16 18:05:45

+0

是的,我想到了这一点,并决定让它更具可读性。谢谢,虽然我误解了这个问题。它说要计算“所有元素”.. ooops。这应该仍然有用。 – 2009-07-16 18:06:55

11
var wordCount = 
    from word in words 
    group word by word into g 
    select new { g.Key, Count = g.Count() };  

这是从一个例子迈出了linqpad

相关问题