【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))}");

结果:

相关推荐
0x00076 分钟前
译 Anders Hejlsberg 谈 C# 与 .NET
开发语言·c#·.net
Xin_ye1008625 分钟前
C# 零基础到精通教程 - 第十七章:前端集成——Blazor 基础
开发语言·c#
daopuyun35 分钟前
《C#语言源代码漏洞测试规范》解读,如何依据GB/T 34946-2017标准建立代码测试技术体系
c#·代码测试·源代码安全检测
魔法阵维护师1 小时前
从零开发游戏需要学习的c#模块,第三十一章(技能冷却系统 —— 范围爆炸)
学习·游戏·c#
吴可可1232 小时前
ModelSpace常量正确用法解析
c#
影寂ldy2 小时前
C#List泛型集合
windows·c#·list
狂人开飞机3 小时前
01. 工厂模式(Factory Pattern)
设计模式·c#
我是唐青枫3 小时前
C#.NET YARP 服务发现实战:接入 Consul 和 Kubernetes 动态发现后端服务
c#·服务发现·.net
魔法阵维护师4 小时前
从零开发游戏需要学习的c#模块,第三十章(掉落物品 —— 血包与能量)
学习·游戏·c#
z落落5 小时前
C# ArrayList 动态集合(接口/区别/API/深浅拷贝)+ List<T> 泛型集合
开发语言·c#