c# - Counting occurrences in Array -


i counting occurrence of each element in array error "value cannot null" doesn't make sense me because arr1 populated no null values except last 5 elements null.

here code. using dictionary first time may have logic error somewhere. reading textfile.

string[] arr1 = new string[200]; streamreader sr = new streamreader("newworksheet.txt"); string templine1 = ""; int counter = 0; while (templine1 != null) {     templine1 = sr.readline();     arr1[counter] = templine1;     counter += 1; } sr.close();  // dictionary, key number list , associated value number of times key found dictionary<string, int> occurrences = new dictionary<string, int>(); // loop test data foreach (string value in arr1) {     if (occurrences.containskey(value)) // check if have found key before     {         // key exists. add number of occurrences key 1         occurrences[value]++;     }     else     {         // new key add it. number 1 indicates key has been found 1 time         occurrences.add(value, 1);     } }  // dump result system.io.streamwriter sr2 = new system.io.streamwriter("organizedversion.txt"); foreach (string key in occurrences.keys) {     sr2.writeline("integer " + key.tostring() + " found " + occurrences[key].tostring() + " times"); } sr2.close(); console.readline(); 

edit: put code here including declaration.

it's not question linq reduce number of lines here:

var groups = arr1.groupby(item => item); foreach (var group in groups) {   console.writeline(string.format("{0} occurences of {1}", group.count(), group.key); } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -