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

结果:

相关推荐
程序猿多布8 小时前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
阿蒙Amon9 小时前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#
开开心心_Every9 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text
我要打打代码12 小时前
C#Winform窗体显示模糊的问题
c#
阿蒙Amon12 小时前
C#正则表达式全面详解:从基础到高级应用
开发语言·正则表达式·c#
水果里面有苹果14 小时前
19-C#静态方法与静态类
java·开发语言·c#
吃着火锅x唱着歌14 小时前
LeetCode 3306.元音辅音字符串计数2
算法·leetcode·c#
秋说15 小时前
【PTA数据结构 | C语言版】在顺序表 list 的第 i 个位置上插入元素 x
c语言·数据结构·list
秋说16 小时前
【PTA数据结构 | C语言版】返回单链表 list 中第 i 个元素值
c语言·数据结构·list
双叶83616 小时前
(C++)任务管理系统(正式版)(迭代器)(list列表基础教程)(STL基础知识)
c语言·开发语言·数据结构·c++·list