我正在尝试为学校项目编写一个程序,该程序将读取每行包含名称的csv文件,并输出每个名称及其在列表框中出现的次数。我希望它不是为特定名称预先设置,但我想这也可以。到目前为止,我有这个,但现在我被卡住了。 CSV文件在每一行上都有一个名称,并且在每个名称后面都有一个昏迷。任何帮助都会非常感谢。
这是我到目前为止所做的:
string[] csvArray;
string line;
StreamReader reader;
OpenFileDialog openFileDialog = new OpenFileDialog();
//set filter for dialog control
const string FILTER = "CSV Files|*.csv|All Files|*.*";
openFileDialog.Filter = FILTER;
//if user opens file and clicks ok
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//open input file
reader = File.OpenText(openFileDialog.FileName);
//while not end of stream
while (!reader.EndOfStream)
{
//read line from file
line = reader.ReadLine().ToLower();
//split values
csvArray = line.Split(',');
答案 0 :(得分:4)
使用Linq,我们可以执行以下操作:
static IEnumerable<Tuple<int,string>> CountOccurences(IEnumerable<string> data)
{
return data.GroupBy(t => t).Select(t => Tuple.Create(t.Count(),t.Key));
}
测试:
var strings = new List<string>();
strings.Add("John");
strings.Add("John");
strings.Add("John");
strings.Add("Peter");
strings.Add("Doe");
strings.Add("Doe");
foreach (var item in CountOccurences(strings)) {
Console.WriteLine (String.Format("{0} = {1}", item.Item2, item.Item1));
}
约翰= 3 彼得= 1 Doe = 2
在您的情况下使用:
string filePath = "c:\myfile.txt"
foreach (var item in CountOccurences(File.ReadAllLines(filePath).Select(t => t.Split(',').First())))
Console.WriteLine (String.Format("{0} = {1}", item.Item2, item.Item1));
答案 1 :(得分:3)
您可以使用字典,您可以在其中存储每个名称的出现次数:
Dictionary<string,int> NameOcur=new Dictionary<string,int>();
...
while (!reader.EndOfStream)
{
//read line from file
line = reader.ReadLine().ToLower();
//split values
csvArray = line.Split(',');
if (NameOcur.ContainsKey(csvArray[0]))
{
///Name exists in Dictionary increase count
NameOcur[csvArray[0]]++;
}
else
{
//Does not exist add with value 1
NameOcur.Add(csvArray[0],1);
}
}