如何使用 C# 檢查陣列是否包含重複數字?


首先,設定一個數組 −

int[] arr = {
   87,
   55,
   23,
   87,
   45,
   23,
   98
};

現在宣告一個字典,並迴圈陣列並獲取所有元素的數量。您從字典中獲得的值顯示了數字的出現 −

foreach(var count in arr) {
   if (dict.ContainsKey(count))
   dict[count]++;
   else
   dict[count] = 1;
}

讓我們來看一個完整的示例 −

示例

using System;
using System.Collections.Generic;
namespace Demo {
   public class Program {
      public static void Main(string[] args) {
     
         int[] arr = {
            87,
            55,
            23,
            87,
            45,
            23,
            98
         };
         var dict = new Dictionary < int, int > ();
         foreach(var count in arr) {
            if (dict.ContainsKey(count))
            dict[count]++;
            else
            dict[count] = 1;
         }
         foreach(var val in dict)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}

更新於: 22-Jun-2020

1 千+ 瀏覽

啟動你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.