实例描述
现有某班学生的两份成绩,两份成绩中存在一些不一致的记录。需借助于编程方法找出这些不一致的记录。
实例代码
using system; using system.collections.generic; using system.linq; namespace intersectandexceptexp { class program { static void main(string[] args) { list<student> studentlist1 = newlist<student>() { 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<student> studentlist2 = newlist<student>() { 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); } } } public class student { public int studentid { get; set; } public int score { get; set; } } public class studentcomparer : iequalitycomparer<student> { public bool equals(student x, studenty) { if (object.referenceequals(x, y)) returntrue; 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; } } }
代码说明
先使用intersect方法生成两份记录的交集,该方法会使用传入的比较器对值进行比较决定记录是否相同。基于前步生成的交集,再使用except方法找出两份记录中不一致的记录,该方法同样使用传入的比较器对值进行比较决定记录是否相同。
执行结果
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论