0

我正在计算数组中每个元素的出现次数,但出现错误“值不能为空”这对我来说没有意义,因为除了最后 5 个为空的元素之外,arr1 完全填充了没有空值。

这是我的代码。我是第一次使用字典,所以我可能在某处有一些逻辑错误。我正在阅读文本文件。

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();

编辑:我把所有的代码都放在这里,包括声明。

4

4 回答 4

5

这不完全是您的问题,但 Linq 可以减少此处的行数:

var groups = arr1.GroupBy(item => item);
foreach (var group in groups)
{
  Console.WriteLine(string.Format("{0} occurences of {1}", group.Count(), group.Key);
}
于 2013-05-13T17:38:39.343 回答
1

“arr1 完全填充,没有空值”

没有。您放入数组的最后一项为空。在将值放入数组之前检查值:

while (true) {
  Templine1 = sr.ReadLine();
  if (Templine1 == null) break;
  arr1[counter++] = Templine1;
}

或者,如果您更喜欢这种方法:

while ((Templine1 = sr.ReadLine()) != null) {
  arr1[counter++] = Templine1;
}

现在,循环到 index counter,而不是循环遍历整个数组,而不管你在其中放入了多少项:

for (int i = 0; i < counter; i++) {
  string value = arr1[i];
  ...
}
于 2013-05-13T17:44:37.937 回答
1

我的钱是arr1空的(基于您应该事先知道大小但您正在填充文件中可能更改的行的事实)。好消息是您实际上并不需要它。

替换这个: foreach (string value in arr1)

... 有了这个:

foreach(string value in File.ReadLines("fileName"))
{
}

MSDN 文件.ReadLines

于 2013-05-13T17:34:57.187 回答
0

在您的循环中,您需要检查null您的价值是否存在

foreach (string value in arr1)
{
     if (!string.IsNullOrEmpty(value))
     {
      ........

这将解决您在文件中可能遇到的问题。

于 2013-05-13T17:40:27.327 回答