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

结果:

相关推荐
江山如画,佳人北望6 小时前
C#程序入门
开发语言·windows·c#
与火星的孩子对话7 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
future14127 小时前
C#每日学习日记
java·学习·c#
军训猫猫头11 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
纳兰青华16 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
云泽野1 天前
【Java|集合类】list遍历的6种方式
java·python·list
葬歌倾城1 天前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue1 天前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王1 天前
hello判断
开发语言·c#
金增辉1 天前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#