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

ตรวจสอบว่า SortedSet มีสมาชิกเฉพาะหรือไม่ใน C#

บทความนี้สาธิตวิธีตรวจสอบว่า SortedSet<T> มีสมาชิก (element) ที่ระบุอยู่หรือไม่ โดยใช้เมธอด Contains() ใน C#

ตัวอย่างที่ 1: ตรวจสอบสมาชิกใน SortedSet ของสตริง

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<string> set1 = new SortedSet<string>();
        set1.Add("CD");
        set1.Add("CD"); // ซ้ำจะถูกเพิ่มเพียงครั้งเดียว
        set1.Add("CD");
        set1.Add("CD");

        Console.WriteLine("Elements in SortedSet1...");
        foreach (string res in set1)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("Does the SortedSet1 contains the element DE? = " + set1.Contains("DE"));

        SortedSet<string> set2 = new SortedSet<string>();
        set2.Add("BC");
        set2.Add("CD");
        set2.Add("DE");
        set2.Add("EF");
        set2.Add("AB");
        set2.Add("HI");
        set2.Add("JK");

        Console.WriteLine("Elements in SortedSet2...");
        foreach (string res in set2)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("SortedSet2 is a superset of SortedSet1? = " + set2.IsSupersetOf(set1));
    }
}

ผลลัพธ์

Elements in SortedSet1...
CD
Does the SortedSet1 contains the element DE? = False
Elements in SortedSet2...
AB
BC
CD
DE
EF
HI
JK
SortedSet2 is a superset of SortedSet1? = True

ตัวอย่างที่ 2: ตรวจสอบสมาชิกใน SortedSet ของจำนวนเต็ม

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> mySet = new SortedSet<int>();
        mySet.Add(100);
        mySet.Add(200);
        mySet.Add(300);
        mySet.Add(400);

        Console.WriteLine("Elements in SortedSet...");
        foreach (int res in mySet)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("Does the SortedSet contains the element 400? = " + mySet.Contains(400));
    }
}

ผลลัพธ์

Elements in SortedSet...
100
200
300
400
Does the SortedSet contains the element 400? = True

สรุป

  • ใช้ Contains(T item) เพื่อตรวจสอบว่ามีสมาชิกอยู่ใน SortedSet หรือไม่ — คืนค่า bool
  • SortedSet จัดเก็บข้อมูล ไม่ซ้ำกัน (unique) และ เรียงลำดับอัตโนมัติ (ascending)
  • การเพิ่มค่าซ้ำ (duplicate) จะถูกละเว้น — set1 ในตัวอย่างมีแค่ "CD" เพียงค่าเดียว
  • เมธอด IsSupersetOf() ตรวจสอบว่าชุดหนึ่งเป็น superset ของอีกชุดหนึ่ง (มีสมาชิกครบทุกตัวของชุดที่เปรียบเทียบ)
  • Complexity ของ Contains() คือ O(log n) เนื่องจากโครงสร้างข้อมูลเป็น balanced tree