便宜VPS主机精选
提供服务器主机评测信息

c# 中 Set 集合并集操作详解:实现高效数据合并技巧

在C#中,要对HashSet进行并集操作,可以使用UnionWith()方法。这是一个例子:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3, 4, 5 };
        HashSet<int> set2 = new HashSet<int> { 4, 5, 6, 7, 8 };

        // 对两个HashSet进行并集操作
        set1.UnionWith(set2);

        // 输出并集后的HashSet
        Console.WriteLine("并集后的HashSet:");
        foreach (int item in set1)
        {
            Console.WriteLine(item);
        }
    }
}

在这个例子中,我们创建了两个HashSet(set1set2),然后使用UnionWith()方法将它们合并。最后,我们遍历并输出合并后的HashSet。

未经允许不得转载:便宜VPS测评 » c# 中 Set 集合并集操作详解:实现高效数据合并技巧