عملگر مجموعه Intersect
در این بخش از آموزش LINQ متد افزودنی Intersect را بررسی خواهیم کرد. این متد برای اجرا شدن به دو مجموعه نیاز دارد و عملکرد آن به این شکل است که عناصر مشترک بین دو مجموعه را باز می گرداند. برای درک بهتر به مثال زیر توجه کنید:
1 2 3 4 5 | IList<string> strList1 = new List<string>() { "One", "Two", "Three", "Four", "Five" }; IList<string> strList2 = new List<string>() { "Four", "Five", "Six", "Seven", "Eight"}; var result = strList1.Intersect(strList2); foreach(string str in result) Console.WriteLine(str); |
خروجی مثال:
1 2 | Four Five |
توجه داشته باشید که زمانی که نوع داده مجموعه از نوع پیچیدهتر باشد متد Intersect نتیجه درستی نمی دهد. برای رفع این مشکل می توانید یک مقایسه کننده سفارشی مانند نمونه زیر که اینترفیس IEqualityComparer را پیادهسازی می کند ایجاد کرده و آن را به متد Intersect ارسال کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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(); } } |
نحوه استفاده از مقایسه کننده سفارشی:
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.Intersect(studentList2, new StudentComparer()); foreach(Student std in resultedCol) Console.WriteLine(std.StudentName); |
خروجی مثال:
1 2 | Bill Ron |
هیچ نظری ثبت نشده است