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

แสดงค่า Unique จาก List ใน C#

ภาพรวม

ใช้ LINQ Distinct() เพื่อกรองค่าที่ซ้ำออกจาก List คืนค่า IEnumerable<T> สามารถแปลงกลับเป็น List ได้ด้วย ToList()

โค้ดตัวอย่าง


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

public class Demo {
    public static void Main() {
        List<int> list = new List<int> { 55, 45, 55, 65, 73, 24, 65 };

        Console.WriteLine("Initial List:");
        list.ForEach(Console.WriteLine);

        // Distinct - ลบซ้ำ
        List<int> uniqueList = list.Distinct().ToList();

        Console.WriteLine("\nUnique elements:");
        uniqueList.ForEach(Console.WriteLine);
    }
}

ผลลัพธ์


Initial List:
55
45
55
65
73
24
65

Unique elements:
55
45
65
73
24

รูปแบบอื่นๆ

1. ใช้ HashSet (เร็วกว่า Distinct สำหรับข้อมูลใหญ่)


var uniqueSet = new HashSet<int>(list);
var uniqueList = uniqueSet.ToList();
// หมายเหตุ: HashSet ไม่รักษาลำดับ

2. รักษาลำดับเดิม (First Occurrence)


// Distinct() รักษาลำดับการปรากฏครั้งแรก
var uniqueOrdered = list.Distinct().ToList(); // 55, 45, 65, 73, 24

3. ใช้ GroupBy (เมื่อต้องการนับความถี่พร้อมกัน)


var uniqueWithCount = list
    .GroupBy(x => x)
    .Select(g => new { Value = g.Key, Count = g.Count() })
    .ToList();

foreach (var item in uniqueWithCount) {
    Console.WriteLine($"{item.Value}: {item.Count} time(s)");
}

4. สำหรับ Object/Class ต้อง Implement IEquatable หรือ IEqualityComparer


public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

// Custom comparer
public class PersonComparer : IEqualityComparer<Person> {
    public bool Equals(Person x, Person y) => x?.Name == y?.Name && x?.Age == y?.Age;
    public int GetHashCode(Person obj) => HashCode.Combine(obj.Name, obj.Age);
}

// ใช้งาน
var people = new List<Person> { ... };
var uniquePeople = people.Distinct(new PersonComparer()).ToList();

สรุป

  • Distinct(): เรียบง่าย รักษาลำดับ ใช้ Default Equality Comparer
  • HashSet: เร็วกว่า แต่ไม่รักษาลำดับ
  • Custom Types: ต้องระบุ IEqualityComparer หรือ implement IEquatable<T>
  • Performance: Distinct() ใช้ HashSet ภายในอยู่แล้ว O(n) average