如何在文本文件中计算相同的名称 [英] how to count same names in textfile
问题描述
我想创建每行包含一个名称的文本文件.计算出现任何名称的次数.为文件中的每个名称输出一行,并在每一行上打印出现次数,后跟名称.
我想在messageBox中显示答案
这是我到目前为止所做的
I wanna create text file containing one name on each line. Compute the number of times any name occurs. Output one line for each name in file and on each line print the number of occurrences followed by name.
and i would like to diplay the answer in messageBox
this is what i have done so far
var nameCount = new Dictionary<string, int>();
foreach (String s in File.ReadAllLines(openFileDialog1.FileName))
{
if (nameCount.ContainsKey(s))
{
nameCount[s] = nameCount[s] + 1;
}
else
{
nameCount.Add(s, 1);
}
}
var output = new StringBuilder();
foreach (var pair in nameCount(openFileDialog1.FileName))
{
MessageBox.Show("{0} {1}\n", pair.Key, pair.Value);
}
但是我仍然有一些错误
but i still have some error
推荐答案
问题出在最后一部分:
The problem is in the last part:
foreach (var pair in nameCount(openFileDialog1.FileName))
{
MessageBox.Show("{0} {1}\n", pair.Key, pair.Value);
}
1)您不需要(openFileDialog1.FileName)位.
2)您需要先格式化字符串,然后才能将其放入信箱:
1) You don''t need the (openFileDialog1.FileName) bit.
2) You need to format your string before you can hand it to a messgae box:
foreach (var pair in nameCount)
{
MessageBox.Show(String.Format("{0} {1}\n", pair.Key, pair.Value));
}
但是我会做些不同:
But I would do it slightly differently:
foreach (string key in nameCount.Keys)
{
MessageBox.Show(string.Format("{0} {1}\n", key, nameCount[key]));
}
我真的希望您不要有太多名字,否则您将整个下午都在按下确定"按钮!
找不到文件"C:\ Users \ acer \ AppData \ Local \ Temporary Projects \ FourthProgramm \ bin \ Debug \ openFileDialog1"."
您是否曾经在OpenFileDialog上调用ShowDialog?
通常是:
And I really hope you don''t have a lot of names, or you will spend all afternoon pressing the "OK" button!
"Could not find file ''C:\Users\acer\AppData\Local\Temporary Projects\FourthProgramm\bin\Debug\openFileDialog1''."
Did you call ShowDialog on the OpenFileDialog at any time?
Normally it would be:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var nameCount = new Dictionary<string, int>();
foreach (String s in File.ReadAllLines(openFileDialog1.FileName))
if (nameCount.ContainsKey(s))
{
nameCount[s] = nameCount[s] + 1;
}
else
{
nameCount.Add(s, 1);
}
var output = new StringBuilder();
foreach (var pair in nameCount)
{
MessageBox.Show(String.Format("{0} {1}\n", pair.Key, pair.Value));
}
}
}
这篇关于如何在文本文件中计算相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!