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

结果:

相关推荐
心平气和量大福大4 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
-银雾鸢尾-8 小时前
C#中HashTable相关方法
开发语言·c#
geovindu12 小时前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
吴可可12312 小时前
C# CAD二次开发中如何退出窗口
c#
影寂ldy12 小时前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
ellis197012 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
-银雾鸢尾-12 小时前
C#中的Dictionary相关方法
开发语言·c#
lzhdim13 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
WarPigs14 小时前
.NET项目app.Config笔记
c#·.net