计算数组中出现的次数
我正在计数数组中每个元素的出现,但出现错误“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
为空(基于事实上,您应该事先知道大小,但您正在填充可能会更改的文件中的行)。好处是你并不需要它。
替换此:foreach (string value in arr1)
...这一点:
foreach(string value in File.ReadLines("fileName"))
{
}
这确实不是你的问题,但LINQ的在这里可以减少行数:
var groups = arr1.GroupBy(item => item);
foreach (var group in groups)
{
Console.WriteLine(string.Format("{0} occurences of {1}", group.Count(), group.Key);
}
是Linq是答案。也许你可以用ToDictionary()添加一个变体。 – 2013-05-13 17:39:34
@HenkHolterman,ToDictionary不会在这里工作,因为有多个项目具有相同的密钥,ToLookup会工作 – 2013-05-13 17:40:25
您可以使用两者来获取计数字典,像'.ToLookup(...)。ToDictionary(x = > x.Key,x => x.Count())'。 'GroupBy'可以代替'ToLookup'工作,如果在这个实例中有所不同,那么不能确定。 – 2013-05-13 17:41:18
在你的循环中你需要检查是否有null
在你的价值
foreach (string value in arr1)
{
if (!string.IsNullOrEmpty(value))
{
........
这将带你可能在文件中的问题护理。
都能跟得上 “ARR1完全没有空值填充”。你放入数组的最后一项是空的。检查的价值,你把它在数组中前:
while (true) {
Templine1 = sr.ReadLine();
if (Templine1 == null) break;
arr1[counter++] = Templine1;
}
或者,如果你喜欢这个方法好:
while ((Templine1 = sr.ReadLine()) != null) {
arr1[counter++] = Templine1;
}
现在,环达指数counter
,而不是通过整个数组循环不管您放入多少物品:
for (int i = 0; i < counter; i++) {
string value = arr1[i];
...
}
显示'arr1'和'counter'的声明和初始化。 – 2013-05-13 17:50:35