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

结果:

相关推荐
Wythzhfrey1 小时前
单片机Day05---静态数码管
c语言·单片机·嵌入式硬件·学习·c#·51单片机
夜月yeyue3 小时前
STM32启动流程详解
linux·c++·stm32·单片机·嵌入式硬件·c#
码观天工3 小时前
解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
性能优化·c#·.net·内存管理·异步·.net 9
Tdm_8884 小时前
SQL Server中OPENJSON + WITH 来解析JSON
java·数据库·sql·c#·json·mssql
观无8 小时前
关于Newtonsoft.Json
c#
唐青枫8 小时前
C# 如何比较两个List是否相等?
c#·.net
搬砖工程师Cola13 小时前
<C#>在 C# .NET 6 中,使用IWebHostEnvironment获取Web应用程序的运行信息。
开发语言·c#·.net
Spring_Lws19 小时前
aslist和list的区别
数据结构·list
CppPlayer-程序员阿杜19 小时前
poll为什么使用poll_list链表结构而不是数组 - 深入内核源码分析
网络·c++·链表·list·poll
@hdd19 小时前
C++| 深入剖析std::list底层实现:链表结构与内存管理机制
c++·链表·list