Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบค่าซ้ำในอาร์เรย์ด้วย Dictionary ใน C#

ภาพรวม

ใช้ Dictionary<TKey, TValue> นับจำนวนครั้งที่แต่ละค่าปรากฏในอาร์เรย์ คีย์คือค่าในอาร์เรย์ ค่าคือจำนวนครั้ง (count)

โค้ดตัวอย่าง


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 value in arr) {
                if (dict.ContainsKey(value))
                    dict[value]++;
                else
                    dict[value] = 1;
            }

            foreach (var kvp in dict) {
                Console.WriteLine($"{kvp.Key} occurred {kvp.Value} times");
            }
        }
    }
}

ผลลัพธ์


87 occurred 2 times
55 occurred 1 times
23 occurred 2 times
45 occurred 1 times
98 occurred 1 times

วิธีที่ทันสมัยกว่า (LINQ GroupBy)


var counts = arr
    .GroupBy(x => x)
    .Select(g => new { Value = g.Key, Count = g.Count() })
    .OrderByDescending(x => x.Count);

foreach (var item in counts) {
    Console.WriteLine($"{item.Value} occurred {item.Count} times");
}

วิธีสั้นที่สุด (LINQ ToLookup)


var lookup = arr.ToLookup(x => x);
foreach (var group in lookup) {
    Console.WriteLine($"{group.Key} occurred {group.Count()} times");
}

การตรวจสอบว่ามีค่าซ้ำหรือไม่ (Boolean)


bool hasDuplicates = arr.Length != arr.Distinct().Count();
// หรือ
bool hasDuplicates = arr.GroupBy(x => x).Any(g => g.Count() > 1);

สรุป

  • Dictionary: เหมาะสำหรับ manual counting, ควบคุม logic เองได้
  • LINQ GroupBy: อ่านง่าย สั้น กระชับ
  • ToLookup: คล้าย GroupBy แต่สร้าง lookup table ใช้ซ้ำได้
  • Distinct().Count(): เร็วที่สุดสำหรับแค่เช็คว่ามีซ้ำหรือไม่