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

ตรวจสอบว่า SortedSet และคอลเลกชันที่ระบุมีองค์ประกอบเหมือนกันทั้งหมดหรือไม่ใน C#

ภาพรวม

เมธอด SortedSet<T>.SetEquals(IEnumerable<T>) ตรวจสอบว่าเซตและคอลเลกชันที่ระบุมีองค์ประกอบ เหมือนกันทุกประการ (เซตเท่ากัน) คืนค่า true หากเท่ากัน false หากต่างกัน

ตัวอย่างที่ 1: เซตที่ไม่มีค่าเหมือนกัน

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        SortedSet<int> set2 = new SortedSet<int>();
        set2.Add(450);
        set2.Add(550);
        set2.Add(650);
        set2.Add(750);
        set2.Add(800);
        Console.WriteLine("Does it contain the same elements? = " + set1.SetEquals(set2));
    }
}

ผลลัพธ์

Does it contain the same elements? = False

ตัวอย่างที่ 2: เซตที่มีองค์ประกอบเหมือนกันทุกประการ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        SortedSet<int> set2 = new SortedSet<int>();
        set2.Add(100);
        set2.Add(200);
        set2.Add(300);
        Console.WriteLine("Does it contain the same elements? = " + set1.SetEquals(set2));
    }
}

ผลลัพธ์

Does it contain the same elements? = True

คำอธิบายเพิ่มเติม

  • SetEquals() ตรวจสอบความเท่ากันของเซต (same elements) ลำดับไม่สำคัญ เพราะ SortedSet เรียงอัตโนมัติ
  • ต่างจาก Overlaps() ที่ตรวจสอบเพียงมีค่าร่วมกันอย่างน้อยหนึ่งค่า
  • พารามิเตอร์รับ IEnumerable<T> ใดๆ ก็ได้
  • ซับซ้อนเวลา O(n) โดย n = จำนวนองค์ประกอบในเซตปัจจุบัน
  • SortedSet ใช้ balanced tree ให้การดำเนินการเซตมีประสิทธิภาพและคงการเรียงลำดับ