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();

执行结果如下:

  

3、取两个List的交集

var resultIntersectList = listA.Intersect(listB);

执行结果如下:

  

4、取两个List的差集,差集是指取在该集合中而不在另一集合中的所有的项

var resultExceptList = listA.Except(listB);

执行结果如下:

  

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

1、先定义一个类

    /// <summary>
    /// 学生类
    /// </summary>
    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();
原文地址:https://www.cnblogs.com/qtiger/p/13475292.html