2009-07-16 57 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

相關問題