C#程式用於從整數列表中列印重複項


要從整數列表中列印重複項,請使用 ContainsKey。

下面,我們首先設定整數。

int[] arr = {
   3,
   6,
   3,
   8,
   9,
   2,
   2
};

然後使用 Dictionary 集合獲得重複整數的計數。

讓我們看看獲取重複整數的程式碼。

範例

 即時演示

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            3,
            6,
            3,
            8,
            9,
            2,
            2
         };
         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);
      }
   }
}

輸出

3 occurred 2 times
6 occurred 1 times
8 occurred 1 times
9 occurred 1 times
2 occurred 2 times

更新於: 22-Jun-2020

768 瀏覽次數

開始你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.