【C#】List求并集、交集、差集

  1. 值类型List
csharp 复制代码
            List<int> intList1 = new List<int>() { 1, 2, 3 };
            List<int> intList2 = new List<int>() { 3, 4, 5 };
            var result = intList1.Union(intList2);
            Console.WriteLine($"并 {string.Join(',',result)}");
             result = intList1.Intersect(intList2);
            Console.WriteLine($"交 {string.Join(',', result)}");
             result = intList1.Except(intList2);
            Console.WriteLine($"差 {string.Join(',', result)}");

结果:

  1. 对象类型List
csharp 复制代码
       List<Person> people = new List<Person>
        {
            new Person { Name = "Alice" },
            new Person { Name = "Bob" },
            new Person { Name = "Charlie" }
        };
        List<Person> people2 = new List<Person>
        {
            new Person { Name = "Alice" },
            new Person { Name = "Joan" }
        };
        var abc = people.Union(people2).ToList();
        Console.WriteLine($"并 { string.Join(',', abc.Select(s => s.Name))}");
        abc = people.Where(s => people2.Any(x => x.Name == s.Name)).ToList();
        Console.WriteLine($"Name交 {string.Join(',', abc.Select(s=>s.Name))}");
        abc = people.Where(s =>!  people2.Any(x => x.Name == s.Name)).ToList();
        Console.WriteLine($"Name差 {string.Join(',', abc.Select(s => s.Name))}");

结果

  1. 对象类型的还可以利用LINQ 左连接求交集、差集
csharp 复制代码
    var leftJoinQuery = from p in people
                        join pp in people2 on p.Name equals pp.Name into temp
                        from co in temp.DefaultIfEmpty()
                        where co is not null
                        select new { p.Name };

    Console.WriteLine($"Name交 {string.Join(',', leftJoinQuery.Select(s => s.Name))}");

    leftJoinQuery = from p in people
                        join pp in people2 on p.Name equals pp.Name into temp
                        from co in temp.DefaultIfEmpty()
                        where co is null 
                        select new { p.Name };

   Console.WriteLine($"Name差 {string.Join(',', leftJoinQuery.Select(s => s.Name))}");

结果:

相关推荐
用户298698530143 小时前
在 PC 上将 HTML 转换为 PDF 的3种有效方法
人工智能·c#·html
Rotion_深5 小时前
C# 设计TCP Server
开发语言·tcp/ip·c#
csdn_aspnet6 小时前
C# 从凸包中删除点(Deleting points from Convex Hull)
开发语言·c#
czhc11400756637 小时前
7.28 从“图形状态切换“理解 Parse 与状态驱动模式
c#
逻极8 小时前
C# 从入门到精通:现代云原生与AI应用开发实战
ai·云原生·c#·.net
geovindu1 天前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
小羊先生car1 天前
RTOS-F429-HAL-(动/静态)任务的创建(2026/7/27)
开发语言·算法·c#
地球驾驶员1 天前
NX二次开发C#-获取体的外表面
开发语言·c#
程序喵大人1 天前
【C++进阶】STL容器与迭代器 - 04 list 和 forward_list 用节点换稳定位置
开发语言·c++·list
向夏威夷 梦断明暄1 天前
从 Bun 的 Rust 重写,看 C# 如何重建 AI 基础设施层
人工智能·rust·c#