Giới thiệu
SortedSet<T> (namespace System.Collections.Generic) là tập hợp không trùng lặp, tự động sắp xếp. Phương thức UnionWith() hợp nhất tập hợp hiện tại với tập hợp khác (phép hợp tập hợp).
Ví dụ 1: Hợp nhất hai SortedSet có phần tử chung
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(50);
set1.Add(100);
set1.Add(150);
Console.WriteLine("SortedSet1 elements...");
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
SortedSet<int> set2 = new SortedSet<int>();
set2.Add(100);
set2.Add(150);
set2.Add(200);
set2.Add(250);
Console.WriteLine("SortedSet2 elements...");
foreach (int ele in set2)
{
Console.WriteLine(ele);
}
Console.WriteLine("Union...");
set1.UnionWith(set2);
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
}
}
Kết quả
SortedSet1 elements... 50 100 150 SortedSet2 elements... 100 150 200 250 Union... 50 100 150 200 250
Ví dụ 2: Hợp nhất hai SortedSet giống hệt nhau
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);
set1.Add(400);
set1.Add(500);
set1.Add(600);
Console.WriteLine("SortedSet1 elements...");
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
SortedSet<int> set2 = new SortedSet<int>();
set2.Add(100);
set2.Add(200);
set2.Add(300);
set2.Add(400);
set2.Add(500);
set2.Add(600);
Console.WriteLine("SortedSet2 elements...");
foreach (int ele in set2)
{
Console.WriteLine(ele);
}
Console.WriteLine("Union...");
set1.UnionWith(set2);
foreach (int ele in set1)
{
Console.WriteLine(ele);
}
}
}
Kết quả
SortedSet1 elements... 100 200 300 400 500 600 SortedSet2 elements... 100 200 300 400 500 600 Union... 100 200 300 400 500 600
Các phép toán tập hợp khác của SortedSet
IntersectWith(other)- Giao (chỉ giữ phần tử chung)ExceptWith(other)- Hiệu (loại bỏ phần tử có trong other)SymmetricExceptWith(other)- Hiệu đối xứng (phần tử chỉ ở một trong hai)IsSubsetOf(other)- Kiểm tra tập conIsSupersetOf(other)- Kiểm tra tập chaOverlaps(other)- Kiểm tra có phần tử chungSetEquals(other)- Kiểm tra bằng nhau