Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

c# - Counting occurrences in Array

I am counting the occurrence of each element in the array but I get the error "Value cannot be null" This doesn't make sense to me because arr1 is fully populated with no null values except the last 5 elements which are null.

Here is my code. I am using dictionary for the first time so I may have some logic error somewhere. I am reading from a 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 is number from the list and the associated value is the number of times the key is found
Dictionary<string, int> occurrences = new Dictionary<string, int>();
// Loop test data
foreach (string value in arr1)
{
    if (occurrences.ContainsKey(value)) // Check if we have found this key before
    {
        // Key exists. Add number of occurrences for this key by one
        occurrences[value]++;
    }
    else
    {
        // This is a new key so add it. Number 1 indicates that this key has been found one 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() + " was found " + occurrences[key].ToString() + " times");
}
sr2.Close();
Console.ReadLine();

Edit: I put all the code here including declaration.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not exactly your question but Linq could reduce the 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...