Union擴(kuò)展方法需要兩個(gè)集合,并返回一個(gè)新集合,其中包含兩個(gè)集合中不同的元素??聪旅娴膶?shí)例。
IList<string> strList1 = new List<string>() { "One", "Two", "three", "Four" }; IList<string> strList2 = new List<string>() { "Two", "THREE", "Four", "Five" }; var result = strList1.Union(strList2); foreach(string str in result) Console.WriteLine(str);
One Two three THREE Four Five
Union擴(kuò)展方法不能為復(fù)雜類型的集合返回正確的結(jié)果。您需要實(shí)現(xiàn)IEqualityComparer接口,以便從Union方法中獲取正確的結(jié)果。
為 Student 類實(shí)現(xiàn)IEqualityComparer接口,如下所示:
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int Age { get; set; } } class StudentComparer : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { if (x.StudentID == y.StudentID && x.StudentName.ToLower() == y.StudentName.ToLower()) return true; return false; } public int GetHashCode(Student obj) { return obj.StudentID.GetHashCode(); } }
現(xiàn)在,您可以在Union擴(kuò)展方法中傳遞上述StudentComparer類以獲得正確的結(jié)果:
示例:Uion運(yùn)算符 - C#
IList<Student> studentList1 = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; IList<Student> studentList2 = new List<Student>() { new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; var resultedCol = studentList1.Union(studentList2, new StudentComparer()); foreach(Student std in resultedCol) Console.WriteLine(std.StudentName);
John Steve Bill Ron
C # & VB.Net 查詢語法不支持聯(lián)合運(yùn)算符。但是,您可以對(duì)查詢變量使用 Union 方法,或者將整個(gè)查詢包裝到方括號(hào)中,然后調(diào)用 Union ()。