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

结果:

相关推荐
唐青枫2 小时前
C#.NET 主机详解
c#·.net
R-G-B8 小时前
【28】C# WinForm入门到精通 ——多文档窗体MDI【属性、方法、实例、源码】【多窗口重叠、水平平铺、垂直平铺、窗体传值】
c#·winform·多文档窗体mdi·多窗口重叠·水平平铺·垂直平铺·窗体传值
LZQqqqqo12 小时前
c#_文件的读写 IO
开发语言·c#
CodeCraft Studio16 小时前
图像处理控件Aspose.Imaging教程:使用 C# 编程将 CMX 转换为 PNG
图像处理·人工智能·c#·aspose·png·图片格式转换·cmx
csdn_aspnet16 小时前
C# 求梯形面积的程序(Program to find area of a Trapezoid)
c#
LZQqqqqo18 小时前
C#_创建自己的MyList列表
java·算法·c#
lzhdim20 小时前
C#开发的Panel里控件拖放例子 - 开源研究系列文章
开发语言·开源·c#
命苦的孩子21 小时前
List 接口
java·数据结构·list·intellij-idea
★YUI★1 天前
学习游戏制作记录(冻结敌人时间与黑洞技能)7.30
学习·游戏·unity·c#
t198751281 天前
C# CAN通信上位机系统设计与实现
开发语言·c#