C# 中使用 Linq Intersect 与 Except 方法对比数据并找出差异记录
在C#开发中,我们经常需要对比两组数据,找出其中不一致的部分。利用Linq提供的Intersect与Except方法,结合自定义的比较器,我们可以高效地处理这类需求。
核心思路
要找出两份数据中的不同记录,我们可以先求出两者的交集(Intersect),然后分别从原始列表中排除这些交集元素,剩下的即为各自独有的差异数据(Except)。
第1步:定义学生模型
首先,我们需要一个包含 StudentId 和 Score 属性的类来模拟学生成绩数据:
public class Student
{
public int StudentId { get; set; }
public int Score { get; set; }
}
第2步:实现自定义比较器
由于默认情况下引用类型的相等性比较基于内存地址,而我们需要按ID和分数来判断是否相同,因此必须实现 IEqualityComparer<Student> 接口:
public class StudentComparer : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
if (Object.ReferenceEquals(x, y)) return true;
return x != null && y != null && x.StudentId == y.StudentId && x.Score == y.Score;
}
public int GetHashCode(Student obj)
{
int hashStudentId = obj.StudentId.GetHashCode();
int hashScore = obj.Score.GetHashCode();
return hashStudentId ^ hashScore;
}
}
第3步:执行交差运算并输出结果
创建两份存在细微差异的成绩列表,然后通过以下步骤获取差异:
- 使用
Intersect(..., new StudentComparer())获取两份成绩相同的记录。 - 对第一份列表调用
Except(both)获取独有的差异项。 - 对第二份列表调用
Except(both)获取另一侧独有的差异项。
using System;
using System.Collections.Generic;
using System.Linq;
namespace IntersectAndExceptExp
{
class Program
{
static void Main(string[] args)
{
List studentList1 = new List() {
new Student(){StudentId=1,Score=64},
new Student(){StudentId=2,Score=85},
new Student(){StudentId=3,Score=78},
new Student(){StudentId=4,Score=94},
new Student(){StudentId=5,Score=90}
};
List studentList2 = new List() {
new Student(){StudentId=1,Score=64},
new Student(){StudentId=2,Score=80},
new Student(){StudentId=3,Score=78},
new Student(){StudentId=4,Score=94},
new Student(){StudentId=5,Score=95}
};
var both = studentList1.Intersect(studentList2,new StudentComparer());
var diff1 =studentList1.Except(both, new StudentComparer());
var diff2 =studentList2.Except(both, new StudentComparer());
Console.WriteLine("-------------下面是两份成绩中不同的记录--------------");
Console.WriteLine("-------------第一份学生成绩--------------");
foreach (var s in diff1)
{
Console.WriteLine("StudentId:"+s.StudentId+";Score:"+s.Score);
}
Console.WriteLine("-------------第二份学生成绩--------------");
foreach (var s in diff2)
{
Console.WriteLine("StudentId:"+ s.StudentId + ";Score:" + s.Score);
}
}
}
// ... Student 及 StudentComparer 代码同上 ...
}
运行效果验证
上述代码执行后,控制台将打印出两份列表中不相同的具体记录。例如 StudentId=2 和 StudentId=5 会在差异输出中体现其分数的变动情况。
以上就是使用C#的Linq进行集合对比与差异分析的详细内容,更多关于C# Linq IntersectExcept用法、IEqualityComparer接口的资料请关注本站其它相关文章!本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













