我正在計數數組中每個元素的出現,但出現錯誤「Value can not be null」這對我來說沒有意義,因爲arr1完全填充了除最後5元素是null。計算數組中出現的次數
這是我的代碼。我第一次使用字典,所以我可能會在某處出現邏輯錯誤。我正在閱讀文本文件。
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();
編輯:我把所有的代碼放在這裏包括聲明。
顯示'arr1'和'counter'的聲明和初始化。 – 2013-05-13 17:50:35