Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Giao của SortedSet với một Collection trong C#

Mục đích

Phương thức SortedSet<T>.IntersectWith(IEnumerable<T> other) giữ lại trong SortedSet hiện tại chỉ những phần tử **cũng có trong** other. Kết quả vẫn được **sắp xếp tự động**.

Ví dụ 1: SortedSet

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet set1 = new SortedSet { 100, 200, 300 };
        SortedSet set2 = new SortedSet { 450, 200, 650, 300, 800 };

        Console.WriteLine($"Set1 bằng Set2? {set1.SetEquals(set2)}"); // False

        set1.IntersectWith(set2);

        Console.WriteLine("\nKết quả Intersection (set1 đã thay đổi, vẫn sorted):");
        foreach (int val in set1) Console.WriteLine(val);
    }
}

Kết quả

Set1 bằng Set2? False

Kết quả Intersection (set1 đã thay đổi, vẫn sorted):
200
300

Ví dụ 2: SortedSet với nhiều phần tử

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet set1 = new SortedSet { "AB", "BC", "CD", "EF", "PQ", "ST" };
        SortedSet set2 = new SortedSet { "BC", "CD", "DE", "EF", "AB", "HI", "JK" };

        Console.WriteLine("Set1:");
        foreach (string s in set1) Console.WriteLine(s);
        Console.WriteLine($"Count: {set1.Count}");

        Console.WriteLine("\nSet2 (duyệt bằng Enumerator):");
        SortedSet.Enumerator enumr = set2.GetEnumerator();
        while (enumr.MoveNext()) Console.WriteLine(enumr.Current);
        Console.WriteLine($"Count: {set2.Count}");

        set1.IntersectWith(set2);

        Console.WriteLine("\nKết quả Intersection:");
        foreach (string s in set1) Console.WriteLine(s);
    }
}

Kết quả

Set1:
AB
BC
CD
EF
PQ
ST
Count: 6

Set2 (duyệt bằng Enumerator):
AB
BC
CD
DE
EF
HI
JK
Count: 7

Kết quả Intersection:
AB
BC
CD
EF

Đặc điểm quan trọng

  • **In-place**: SortedSet hiện tại bị thay đổi.
  • **Tự động sắp xếp**: Kết quả luôn theo thứ tự tăng dần (theo Comparer).
  • Chấp nhận bất kỳ IEnumerable<T> (List, Array, HashSet, SortedSet...).
  • Phức tạp: O(m log n) với m = other.Count, n = this.Count (do tìm kiếm binary tree).

So sánh với HashSet.IntersectWith

Đặc điểmHashSet.IntersectWithSortedSet.IntersectWith
Kết quả có thứ tựKhôngCó (tăng dần)
Phức tạp (other là HashSet)O(n)O(m log n)
Bộ nhớThấp hơnCao hơn (cây)

Ví dụ: Giữ nguyên SortedSet gốc (Clone)

SortedSet original = new SortedSet { 1, 2, 3, 4, 5 };
SortedSet copy = new SortedSet(original); // Shallow copy
copy.IntersectWith(new[] { 3, 4, 5, 6 });

Console.WriteLine("Original: " + string.Join(", ", original)); // 1, 2, 3, 4, 5
Console.WriteLine("Copy after intersect: " + string.Join(", ", copy)); // 3, 4, 5