用來查詢陣列中是否包含重複元素的 C# 程式


設定陣列 −

int[] arr = {
   89,
   12,
   56,
   89,
};

現在,建立新的字典 −

var d = new Dictionary < int, int > ();

使用字典方法 ContainsKey(),查詢陣列中的重複元素 −

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

以下是完整程式碼 −

示例

 線上演示

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            89,
            12,
            56,
            89,
         };
         var d = new Dictionary < int, int > ();

         foreach(var res in arr) {
            if (d.ContainsKey(res))
            d[res]++;
            else
            d[res] = 1;
         }
         foreach(var val in d)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}

輸出

89 occurred 2 times
12 occurred 1 times
56 occurred 1 times

更新時間: 22-Jun-2020

1 千次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始吧
廣告