عملگر مجموعه Union
در این بخش از آموزش LINQ متد افزودنی Union را بررسی خواهیم کرد. این متد برای اجرا شدن به دو مجموعه نیاز دارد و عملکرد آن به این شکل است که یک مجموعه جدید از ترکیب دو مجموعه ایجاد می کند. البته عناصر تکراری حذف می شوند. مثلا اگر چند مورد از یک عنصر وجود داشته باشد فقط یک مورد از آن در مجموعه نتیجه خواهد بود. برای درک بهتر به مثال زیر توجه کنید:
1 2 3 4 5 | 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); |
خروجی مثال:
1 2 3 4 5 6 | One Two three THREE Four Five |
توجه داشته باشید که این متد نمی تواند عناصری که نوع داده پیچیده تری دارند را مقایسه کند بنابراین باید یک مقایسه کننده سفارشی که اینترفیس IEqualityComparer را پیاده می کند را ایجاد کرده و از آن استفاده کنیم. مانند نمونه زیر:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(); } } |
برای استفاده از مقایسه کننده سفارشی می توانید مانند مثال زیر آن را به عنوان پارامتر به متد افزودنی Union ارسال کنید:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); |
خروجی مثال:
1 2 3 4 | John Steve Bill Ron |
توجه داشته باشید که عملگر Union در سینتکس کوئری پشتیبانی نمی شود.
هیچ نظری ثبت نشده است