Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Distinct() ของ LINQ ใน C#

เมธอด Distinct() คืนลำดับใหม่ที่มีเฉพาะองค์ประกอบที่ไม่ซ้ำกัน (Unique) ตามค่าเริ่มต้นจะใช้ Default Equality Comparer

ตัวอย่าง: ลบค่าซ้ำจาก List

using System;
using System.Linq;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        List points = new List { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 };
        IEnumerable res = points.AsQueryable().Distinct();
        
        foreach (int a in res) Console.WriteLine(a);
    }
}

ผลลัพธ์

5
10
20
30
40
50
60
70

กำหนด Comparer เอง: สามารถส่ง IEqualityComparer<T> เข้าไปเพื่อกำหนดกฎความเท่าเทียมเองได้