Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

In giá trị duy nhất từ List trong C#

Lấy các phần tử duy nhất (distinct) từ List: dùng Distinct() của LINQ hoặc HashSet.

Ví dụ minh họa

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

class Program
{
    static void Main()
    {
        var list = new List { 55, 45, 55, 65, 73, 24, 65 };
        
        Console.WriteLine("List gốc:");
        Console.WriteLine(string.Join(", ", list));
        
        // Cách 1: LINQ Distinct() - giữ thứ tự xuất hiện đầu tiên
        var distinctList = list.Distinct().ToList();
        Console.WriteLine("\nDistinct (LINQ):");
        Console.WriteLine(string.Join(", ", distinctList));
        
        // Cách 2: HashSet - không giữ thứ tự, nhanh hơn cho tập lớn
        var hashSet = new HashSet(list);
        Console.WriteLine("\nHashSet:");
        Console.WriteLine(string.Join(", ", hashSet));
        
        // Cách 3: GroupBy - xem tần suất
        Console.WriteLine("\nTần suất:");
        foreach (var group in list.GroupBy(x => x).OrderBy(g => g.Key))
        {
            Console.WriteLine($"{group.Key}: {group.Count()} lần");
        }
    }
}

Kết quả đầu ra

List gốc:
55, 45, 55, 65, 73, 24, 65

Distinct (LINQ):
55, 45, 65, 73, 24

HashSet:
55, 45, 65, 73, 24

Tần suất:
24: 1 lần
45: 1 lần
55: 2 lần
65: 2 lần
73: 1 lần

Chọn cách nào? Distinct() giữ thứ tự, dùng cho UI. HashSet nhanh hơn O(1) lookup, dùng cho logic nội bộ.