عملگر مجموعه Distinct
در این بخش از آموزش LINQ عملگر Distinct را بررسی خواهیم کرد. این عملگر عناصر تکراری را از مجموعه حذف کرده و عناصر منحصر به فرد را باز میگرداند. در مثال زیر با استفاده از متد افزودنی Distinct عناصر غیر تکراری در مجموعه گرفته و چاپ می شوند:
1 2 3 4 5 6 7 8 | IList<string> strList = new List<string>(){ "One", "Two", "Three", "Two", "Three" }; IList<int> intList = new List<int>(){ 1, 2, 3, 2, 4, 4, 3, 5 }; var distinctList1 = strList.Distinct(); foreach(var str in distinctList1) Console.WriteLine(str); var distinctList2 = intList.Distinct(); foreach(var i in distinctList2) Console.WriteLine(i); |
خروجی مثال:
1 2 3 4 5 6 7 8 | One Two Three 1 2 3 4 5 |
توجه داشته باشید که این متد نمی تواند عناصری که نوع داده پیچیده تری دارند را مقایسه کند بنابراین باید یک مقایسه کننده سفارشی که اینترفیس IEqualityComparer
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(); } } |
برای استفاده از مقایسه کننده سفارشی می توانید مانند مثال زیر آن را به عنوان پارامتر به متد افزودنی Distinct ارسال کنید:
1 2 3 4 5 6 7 8 9 10 11 12 | IList<Student> studentList = 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 = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; var distinctStudents = studentList.Distinct(new StudentComparer()); foreach(Student std in distinctStudents) Console.WriteLine(std.StudentName); |
خروجی مثال:
1 2 3 4 | John Steve Bill Ron |
توجه داشته باشید که عملگر Distinct در سینتکس کوئری مربوط به زبان سی شارپ پشتیبانی نمی شود اما در زبان VB.NET پشتیبانی می شود. مثال:
1 2 3 | Dim strList = New List(Of string) From {"One", "Three", "Two", "Two", "One" } Dim distinctStr = From s In strList _ Select s Distinct |
هیچ نظری ثبت نشده است