[英]Count the number of occurrence of every word in a c# windows forms listbox
I want to count the number of occurrence of every word that is in a listbox. 我想计算列表框中每个单词的出现次数。
This is my function that count the occurrence 这是我计算发生次数的功能
public int CountWords(ArrayList list, string item)
{
int count = 0;
foreach (string str in list)
{
if (item == str)
count++;
}
return count;
}
And this is where i use CountWords -> 这是我使用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);
}
}
If in the listbox i have this values: 如果在列表框中,我具有以下值:
hi 嗨
its 它的
me 我
me 我
the result is this: 结果是这样的:
The counts are right but i want the result to be like this: 计数是正确的,但我希望结果是这样的:
What should i add or remove from the code? 我应该在代码中添加或删除什么?
I'll appreciate any kind of help :) 我将不胜感激:)
Edit : 编辑 :
I'm not able to use the Count() method. 我无法使用Count()方法。
You can count the occurrence of items simply this way: 您可以通过以下方式简单地计算项目的发生:
listBox2.DataSource = listBox1.Items.Cast<object>().GroupBy(x => x)
.Select(x => $"{x.Key}:{x.Count()}").ToList();
You can achieve your requirement very easily using Linq GroupBy 您可以使用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());
}
Version without 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);
}
}
replace this 取代这个
foreach (string str in arrList)
{
count = obj.CountWords(arrList, str);
listBox3.Items.Add(str + ": " + count);
}
with this 有了这个
foreach (string str in arrList)
{
string_Item=string.Concat(str,":",obj.CountWords(arrList, str));
if (!listBox3.Items.Contains(_Item))
{
listBox3.Items.Add(_Item);
}
}
您可以使用Distinct
foreach (string str in arrList.Distinct())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.