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

HashSet ใน C#

HashSet ใน C#

HashSet<T> เป็นคอลเลกชันที่เก็บค่าที่ไม่ซ้ำกัน (Unique) และมีประสิทธิภาพสูงสำหรับการค้นหา เพิ่ม และลบข้อมูล (O(1) Average) ใช้ใน Namespace System.Collections.Generic

ตัวอย่าง: ลบค่าซ้ำในอาร์เรย์

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] arr1 = { "bus", "truck", "bus", "car", "truck" };
        Console.WriteLine("Before: " + string.Join(",", arr1));
        // bus,truck,bus,car,truck

        // ใช้ HashSet กำจัดค่าซ้ำ
        var hashSet = new HashSet(arr1);
        string[] arr2 = hashSet.ToArray();

        Console.WriteLine("After: " + string.Join(",", arr2));
        // bus,truck,car
    }
}

ผลลัพธ์

Before: bus,truck,bus,car,truck
After: bus,truck,car

เมธอดสำคัญของ HashSet

เมธอดคำอธิบาย
Add(T)เพิ่มองค์ประกอบ (คืนค่า false หากมีอยู่แล้ว)
Remove(T)ลบองค์ประกอบ
Contains(T)ตรวจสอบว่ามีองค์ประกอบหรือไม่
UnionWithยูเนียนกับคอลเลกชันอื่น
IntersectWithหาส่วนร่วมกับคอลเลกชันอื่น
ExceptWithลบองค์ประกอบที่อยู่ในคอลเลกชันอื่น
IsSubsetOfตรวจสอบว่าเป็น Subset หรือไม่

เมื่อไหร่ควรใช้ HashSet

  • ต้องการเก็บค่าที่ไม่ซ้ำกัน (Unique values)
  • ต้องการตรวจสอบความมีอยู่ (Contains) บ่อยๆ
  • ต้องการดำเนินการ Set Operations (Union, Intersect, Difference)
  • ไม่สนใจลำดับของข้อมูล