本文介绍了计数出现在阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我指望阵列中的每个元素的发生,但我得到的错误值不能为空这是没有意义的,我因为ARR1是完全没有空值填充除了最后5个元素这是空。
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();
编辑:我把这里所有的代码,包括声明。
I put all the code here including declaration.
推荐答案
这不正是你的问题,但LINQ的可以减少这里的行数:
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);
}
这篇关于计数出现在阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!