2015-07-22 85 views
0

我正在尝试编写一个学校项目的程序,该程序将读取每行包含名称的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

我将有一个行,以便对每个名称和逗号分隔新行一个名称。 – nzimpossible

回答

1

不知道你的全CSV结构,我会做这样的事情:

//outside of loop 
var nameCounterDict = new Dictionary<string, int>(); 

//in loop 
//csvName is the name of the current csv token you're parsing 
int itemCount = 0; 

if(!nameCounterDict.TryGetValue(csvName, out itemCount)) 
    nameCounterDict.Add(csvName, 0) 

nameCounterDict[csvName]++; 

这填充一个独特的名字的每次出现字典,如果名称已经存在,它将增加一个int数。

解析完文件后,可以循环查看字典以获取每个名称和显示的计数器。