【问题标题】:Count the number of occurrence of every word in a c# windows forms listbox计算 c# windows 表单列表框中每个单词的出现次数
【发布时间】:2017-10-08 13:05:26
【问题描述】:

我想计算列表框中每个单词的出现次数。
这是我计算发生次数的函数

public int CountWords(ArrayList list, string item)
{
    int count = 0;
    foreach (string str in list)
    {
        if (item == str)
            count++;
    }
    return count;
}  

这就是我使用 CountWords ->

private void button4_Click(object sender, EventArgs e)
{
    listBox3.Items.Clear();
    ArrayList arrList = new ArrayList();
    int count = 0;
    foreach (object item in listBox2.Items)
    {
        arrList.Add(item);
    }

    foreach (string str in arrList)
    {
        count = obj.CountWords(arrList, str);
        listBox3.Items.Add(str + ": " + count);
    }

}  

如果在列表框中我有这个值:
hi
its
me

结果是这样的:

计数是正确的,但我希望结果是这样的:

我应该在代码中添加或删除什么?
我会很感激任何帮助:)

编辑
我无法使用 Count() 方法。

【问题讨论】:

  • 你为什么使用ArrayList?为什么不是数组或列表? str.Distinct().ToList();应该删除重复项,但返回一个列表。

标签: c# .net winforms listbox


【解决方案1】:

您可以这样简单地计算项目的出现次数:

listBox2.DataSource = listBox1.Items.Cast<object>().GroupBy(x => x)
                              .Select(x => $"{x.Key}:{x.Count()}").ToList();

【讨论】:

    【解决方案2】:

    替换这个

     foreach (string str in arrList)
            {
                count = obj.CountWords(arrList, str);
                listBox3.Items.Add(str + ": " + count);
            }
    

    有了这个

     foreach (string str in arrList)
                    {
                          string_Item=string.Concat(str,":",obj.CountWords(arrList, str));
    
    
                        if (!listBox3.Items.Contains(_Item))
                        {
                            listBox3.Items.Add(_Item);
                        }
                    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 Linq GroupBy 轻松实现您的要求

      private void button4_Click(object sender, EventArgs e)
      {
          listBox3.Items.Clear();
          var temp = listBox2.Items.Cast<string>().GroupBy(s => s);
          foreach(var g in temp)
              listBox3.Items.Add(g.Key + ": " + g.Count());
      } 
      

      不带 Count() 的版本

      private void button4_Click(object sender, EventArgs e)
      {
          listBox3.Items.Clear();
          var temp = listBox2.Items.Cast<string>().GroupBy(s => s);
          foreach(var g in temp)
          {
              int count = 0; foreach(string s in g) count++;
              listBox3.Items.Add(g.Key + ": " + count);
          }
      } 
      

      【讨论】:

      • 这很好用,但我忘了在帖子中写我不能使用 Count() 方法。
      • 然后添加你的循环: int count = 0; foreach(string s in g) count++;
      【解决方案4】:

      你可以使用 Distinct

      foreach (string str in arrList.Distinct())
      

      【讨论】:

        猜你喜欢
        • 2021-04-19
        • 1970-01-01
        • 2021-10-15
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        • 2013-12-25
        • 2021-02-05
        • 1970-01-01
        相关资源
        最近更新 更多