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 方法
如下:
- 方法一
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();
}
}
- 方法二重写一个类让它继承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()
原文地址:https://www.cnblogs.com/xinianxinqix/p/9204534.html
时间: 2024-11-05 16:03:35