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

结果:

相关推荐
星河队长1 小时前
C#实现智能提示输入,并增色显示
开发语言·c#
海木漄2 小时前
C# 内存是绝对自动清理吗?
开发语言·c#
我是唐青枫2 小时前
C#.NET PeriodicTimer 深入解析:高效异步定时器的正确打开方式
c#·.net
技术支持者python,php3 小时前
ModbusRtc与ModbusTCP,esp32
c#
咕白m6254 小时前
如何用 C# 将 Excel 文件转换为 HTML 格式?
c#·.net
weixin_307779134 小时前
C#程序实现将Teradata的存储过程转换为Amazon Redshift的pgsql的存储过程
数据库·c#·云计算·运维开发·aws
是萝卜干呀4 小时前
Backend - HTTP请求的常用返回类型(asp .net core MVC)
http·c#·.netcore·iactionresult
错把套路当深情5 小时前
Kotlin List扩展函数使用指南
开发语言·kotlin·list
爱吃小胖橘13 小时前
Unity资源加载模块全解析
开发语言·unity·c#·游戏引擎
时光追逐者14 小时前
全面的 C#/.NET 图表构建解决方案,助力快速实现图表开发需求!
微软·c#·.net·.net core·图表