【问题标题】:How to count how many times two words occur in a list c# [duplicate]如何计算列表中两个单词出现的次数c# [重复]
【发布时间】:2013-11-26 04:49:09
【问题描述】:

我正在寻找如何为列表中以相同顺序出现的两个单词创建一个计数器。由于单词可能会有所不同(我正在使用 Console.ReadLine 输入它们)我不知道该怎么做。我的列表格式例如:

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

【问题讨论】:

  • 不确定您要做什么/为什么要这样做...
  • @Noctis 我会在运行程序时尝试上传它的屏幕截图
  • 您转到list.Count - 1,然后将一个添加到i,这样您将在集合的最后一次迭代中得到一个异常。

标签: c# list count counter


【解决方案1】:

List(T).FindAll 方法就是你想要的。

示例代码可在此处获得 http://msdn.microsoft.com/en-us/library/fh1w7y8z(v=vs.110).aspx

【讨论】:

    【解决方案2】:

    您可以将字典用于此类操作

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

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 2019-06-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多