2013-11-26 129 views
0

我在找出如何在列表中以相同的顺序出现两个单词的计数器。由于单词可能会有所不同(我正在使用Console.ReadLine输入它们),所以我无法弄清楚该怎么做。我的列表格式,例如:如何计算在一个列表中出现两个单词的次数c#

list[0] : list[1] (1) //this is where i want count 
list[1] : list[2](1) 

这么说的话是:

Hello : I 
am : John 
Hello : I 


![when the program runs](http://imgur.com/HelGjxV) 

顺便说一句写的第二句是我打出来。当第二个Hello:I被输入到列表中。我怎么能设置柜台(1)更新到2.任何帮助将不胜感激。我会包含我的相关代码迄今:

List<string> list = new List<string>(); 
list.AddRange(words); 
list.AddRange(words1); 

//counts total number of words in list. 
int count = 0; 
count = list.Count(d => list.Contains(d)); 

//Displays occurance 
for (int i = 0; i < list.Count - 1; i++) 
    list[i] = string.Format("{0} : {1}", list[i], list[i + 1]); 

list.ForEach(Console.WriteLine); 
+0

不知道什么/你为什么要做? – Noctis

+0

@Noctis我会试着上传它的屏幕截图时,我 – user3034630

+0

你去运行程序' list.Count - 1“,但随后在”i“中加上一个,这样您在最后一次迭代中会遇到异常。 –

回答

0

您可以使用字典对于这些类型的opearion

Dictionary<string,List<int>> dict = new Dictionary<string,List<int>>(); 
if(dict.ContainsKey(wordkey)) 
    //update the key 
    dict[word].Add(newIndex); 
else 
{ 
    var newList = new List(); 
    newList.Add(index); 
    dict.Add(worditem,newList); 
} 
相关问题