我有一个包含以下结果的数组
red
red
red
blue
blue
Green
White
Grey
Run Code Online (Sandbox Code Playgroud)
我希望获得数组的每个值的重复计数,例如:
red Count=3
blue Count=2
Green Count=1
White Count=1
Grey Count=1
Run Code Online (Sandbox Code Playgroud) 我正在计算数组中每个元素的出现但我得到错误"值不能为空"这对我没有意义,因为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 …Run Code Online (Sandbox Code Playgroud)