使用Linq的Intersect与Except方法的实例

来源:互联网 发布:mac跳过打开软件验证 编辑:程序博客网 时间:2024/05/22 01:46

实例描述

现有某班学生的两份成绩,两份成绩中存在一些不一致的记录。需借助于编程方法找出这些不一致的记录。

实例代码

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace IntersectAndExceptExp  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             List<Student> studentList1 = newList<Student>() {  
  11.                 new Student(){StudentId=1,Score=64},  
  12.                 new Student(){StudentId=2,Score=85},  
  13.                 new Student(){StudentId=3,Score=78},  
  14.                 new Student(){StudentId=4,Score=94},  
  15.                 new Student(){StudentId=5,Score=90}  
  16.             };  
  17.             List<Student> studentList2 = newList<Student>() {  
  18.                 new Student(){StudentId=1,Score=64},  
  19.                 new Student(){StudentId=2,Score=80},  
  20.                 new Student(){StudentId=3,Score=78},  
  21.                 new Student(){StudentId=4,Score=94},  
  22.                 new Student(){StudentId=5,Score=95}  
  23.             };  
  24.             var both = studentList1.Intersect(studentList2,new StudentComparer());  
  25.             var diff1 =studentList1.Except(both, new StudentComparer());  
  26.             var diff2 =studentList2.Except(both, new StudentComparer());  
  27.             Console.WriteLine("-------------下面是两份成绩中不同的记录--------------");  
  28.             Console.WriteLine("-------------第一份学生成绩--------------");  
  29.             foreach (var s in diff1)  
  30.             {  
  31.                 Console.WriteLine("StudentId:"+s.StudentId+";Score:"+s.Score);  
  32.             }  
  33.             Console.WriteLine("-------------第一份学生成绩--------------");  
  34.             foreach (var s in diff2)  
  35.             {  
  36.                 Console.WriteLine("StudentId:"+ s.StudentId + ";Score:" + s.Score);  
  37.             }  
  38.         }  
  39.     }  
  40.     public class Student  
  41.     {  
  42.         public int StudentId { getset; }  
  43.         public int Score { getset; }  
  44.     }  
  45.     public class StudentComparer : IEqualityComparer<Student>  
  46.     {  
  47.         public bool Equals(Student x, Studenty)  
  48.         {  
  49.             if (Object.ReferenceEquals(x, y)) returntrue;  
  50.             return x != null && y != null&& x.StudentId == y.StudentId && x.Score == y.Score;  
  51.         }  
  52.         public int GetHashCode(Student obj)  
  53.         {  
  54.             int hashStudentId =obj.StudentId.GetHashCode();  
  55.             int hashScore =obj.Score.GetHashCode();  
  56.             return hashStudentId ^ hashScore;  
  57.         }  
  58.     }  
  59. }  

代码说明

先使用Intersect方法生成两份记录的交集,该方法会使用传入的比较器对值进行比较决定记录是否相同。基于前步生成的交集,再使用Except方法找出两份记录中不一致的记录,该方法同样使用传入的比较器对值进行比较决定记录是否相同。

执行结果