码迷,mamicode.com
首页 > Windows程序 > 详细

C# 两个集合比较差值 Linq的Except的用法

时间:2018-06-20 18:48:12      阅读:4977      评论:0      收藏:0      [点我收藏+]

标签:lse   linq   没有   lis   i++   false   参数   值类型   string   

C# 两个集合比较差值 Linq的Except的用法

值类型的集合比较差值

    List<string> strList1 = new List<string>(){"a", "b", "c", "d"};
    List<string> strList2 = new List<string>() { "a", "b", "f", "e"};

    var strList3 = strList1.Except(strList2).ToList();
    for (int i = 0; i < strList3.Count; i++)
    {
        Console.WriteLine(strList3[i]);
    }

输出的结果是 c d

var strList3 = strList1.Except(strList2).ToList();

这里的意思是strList1中哪些是strList2中没有的,并将获得的差值存放在strList3 (即:strList1中有,strList2中没有)

var strList3 = strList2.Except(strList1).ToList();

这样输出的结果就是 f e

这里将strList1与strList2位置对调下,就是strList2中哪些是strList1中没有的存放在strList3 (即:strList2中有,strList1中没有)

引用类型的集合比较差值

首先创建Student类

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

然后创建2个List

    List<Student> studentList1=new List<Student>()
    {
        new Student(){Id = 1,Name = "小明"},
        new Student(){Id = 2,Name = "小刚"},
        new Student(){Id = 3,Name = "小红"},
    };

    List<Student> studentList2 = new List<Student>()
    {
        new Student(){Id = 1,Name = "小明"}
    };

    var studentList3 = studentList1.Except(studentList2).ToList();
    for (int i = 0; i < studentList3.Count; i++)
    {
        Console.WriteLine($"学号: {studentList3[i].Id} 姓名: {studentList3[i].Name}");
    }

结果输出

学号: 1 姓名: 小明
学号: 2 姓名: 小刚
学号: 3 姓名: 小红

这是因为Except通过使用默认的相等比较器对值进行比较,生成两个序列的差集,需要重写 Equals和GetHashCode 方法

如下:

  1. 方法一
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public override bool Equals(object obj)
        {
            if (obj is Student)
            {
                Student student = obj as Student;
                return Id == student.Id && Name == student.Name;
            }
            return false;
        }
        public override int GetHashCode()
        {
            return Id.GetHashCode() ^ Name.GetHashCode();
        }
    }
  1. 方法二重写一个类让它继承IEqualityComparer
    public class StudentComparer: IEqualityComparer<Student>
    {
        public bool Equals(Student x, Student y)
        {
            return x.Id == y.Id && x.Name == y.Name;
        }

        public int GetHashCode(Student obj)
        {
            return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
        }
    }

***** 特别注意

var studentList3 = studentList1.Except(studentList2,new StudentComparer()).ToList();

这里需要加上参数 new StudentComparer()

C# 两个集合比较差值 Linq的Except的用法

标签:lse   linq   没有   lis   i++   false   参数   值类型   string   

原文地址:https://www.cnblogs.com/xinianxinqix/p/9204534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!