温馨提示×

C#中怎么用Intersect方法过滤数据

c#
小亿
88
2024-04-02 10:03:05
栏目: 编程语言

在C#中,可以使用LINQ的Intersect方法来过滤数据。Intersect方法用于返回两个集合的交集,即返回同时存在于两个集合中的元素。以下是一个示例代码,演示如何使用Intersect方法过滤数据:

using System;
using System.Linq;
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> { 3, 4, 5, 6, 7 };

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

        foreach (int num in intersectList)
        {
            Console.WriteLine(num);
        }
    }
}

在上面的示例中,我们首先创建了两个包含整数的列表list1和list2。然后使用Intersect方法获取这两个列表的交集,结果存储在intersectList中。最后,遍历intersectList并输出结果。最终的输出结果将包含两个列表中同时存在的元素3、4和5。

0