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