0

配列内の各要素の出現をカウントしていますが、「値を null にすることはできません」というエラーが表示されます。arr1 には null である最後の 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();

編集:宣言を含むすべてのコードをここに置きます。

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 は null 値なしで完全に設定されています」

いいえ。配列に入れる最後の項目は null です。配列に入れる前に値を確認してください。

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

または、この方法が気に入った場合:

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

counterここで、入れたアイテムの数に関係なく、配列全体をループするのではなく、 index までループします。

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