返回

C# List取交集的三种方法及性能对比

2024-04-22 C# List 交集 2378 0

在C#中,如果你想从一个List中取另一个List的交集,你可以使用几种不同的方法。以下是三种常见的方法:

1 使用LINQ的Intersect方法

Intersect是LINQ提供的一个方法,它可以直接用于获取两个集合的交集。

using System.Collections.Generic;
using System.Linq;

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

        var intersection = list1.Intersect(list2).ToList();

        Console.WriteLine("Intersection using LINQ Intersect:");
        foreach (var item in intersection)
        {
            Console.WriteLine(item);
        }
    }
}

2 使用HashSet

HashSet是一个不包含重复元素的集合,可以用来进行集合运算,包括交集。

using System.Collections.Generic;

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

        HashSet<int> set1 = new HashSet<int>(list1);
        HashSet<int> set2 = new HashSet<int>(list2);

        var intersection = new HashSet<int>(set1.Intersect(set2));

        Console.WriteLine("Intersection using HashSet:");
        foreach (var item in intersection)
        {
            Console.WriteLine(item);
        }
    }
}

3 使用双重循环

虽然这种方法在效率上可能不如LINQ或HashSet,但对于学习目的或者小集合来说,它仍然是一个可行的方法。

using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> list2 = new List<int> { 4, 5, 6, 7, 8 };
        List<int> intersection = new List<int>();

        foreach (var item1 in list1)
        {
            foreach (var item2 in list2)
            {
                if (item1.Equals(item2))
                {
                    intersection.Add(item1);
                    break; // 找到匹配的项后,跳出内层循环
                }
            }
        }

        // 去除可能的重复项(如果交集中有重复数字)
        intersection = intersection.Distinct().ToList();

        Console.WriteLine("Intersection using nested loops:");
        foreach (var item in intersection)
        {
            Console.WriteLine(item);
        }
    }
}

请注意,双重循环方法在处理大集合时效率较低,因为它需要进行n*m次比较,其中n和m分别是两个集合的大小。而LINQ的Intersect方法和HashSet方法通常会有更好的性能,特别是当处理大型数据集时。

顶部