C# List间的交集并集差集

一、简单类型List的交集并集差集

1、先定义两个简单类型的List

List<int> listA = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
List<int> listB = new List<int>() { 1, 2, 3, 4, 9 };

2、取两个List的并集
var resultUnionList= listA.Union(listB).ToList();
执行结果如下:1, 2, 3, 4, 5, 6, 7, 8, 9

3、取两个List的交集
var resultIntersectList = listA.Intersect(listB);
执行结果如下:1, 2, 3, 4

4、取两个List的差集,差集是指取在该集合中而不在另一集合中的所有的项
var resultExceptList = listA.Except(listB);
执行结果如下:5, 6, 7, 8

二、对象List集合的交集并集差集

1、先定义一个类

//学生类
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Sex { get; set; }
}

2、定义两个List

//LISTA
List<Student> stuListA = new List<Student>();
stuListA.Add(new Student
{
    Name = "A1",
    Age = 10,
    Sex = "男"
});
stuListA.Add(new Student
{
    Name = "A2",
    Age = 11,
    Sex = "男"
});

//LISTB
List<Student> stuListB = new List<Student>();
stuListB.Add(new Student
{
    Name = "B1",
    Age = 10,
    Sex = "女"
});
stuListB.Add(new Student
{
    Name = "B2",
    Age = 11,
    Sex = "男"
});  

3、取上述两个list集合的并集
var result = stuListA.Union(stuListB).ToList();

4、取上述两个list集合的交集,应为是对象集合,可以根据一定规则 Func<TSource, bool> predicate限定那些属于交集
  (1)取两个对象集合中对象名称一样的交集
var result = stuListA.Where(x => stuListB.Any(e => e.Name == x.Name)).ToList();
  
  (2)取两个对象集合中对象名称、对象年龄、对象性别都一样的交集
var result = stuListA.Where(x => stuListB.Any(e => e.Name == x.Name && e.Age == x.Age && e.Sex == x.Sex)).ToList();

5、取上述两个list集合的差集,可以根据一定规则 Func<TSource, bool> predicate限定那些属于差集

  (1)取差集,根据两个对象集合中对象名称一样的规则取差集
var result = stuListA.Where(x =>! stuListB.Any(e => e.Name == x.Name)).ToList();

  (2)取差集,根据两个对象集合中对象名称、对象年龄、对象性别都一样的规则取差集
var result = stuListA.Where(x => !stuListB.Any(e => e.Name == x.Name && e.Age == x.Age && e.Sex == x.Sex)).ToList();

posted on   糯米白白  阅读(7141)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示