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

HashSet (Collection Set) trong C#


HashSet loại bỏ chuỗi/phần tử trùng lặp trong mảng. Là optimized set collection.

Ví dụ loại bỏ trùng lặp

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
    static void Main() {
        string[] arr1 = { "one", "two", "two", "one", "three" };
        Console.WriteLine(string.Join(",", arr1));
        var h = new HashSet<string>(arr1);
        string[] arr2 = h.ToArray();
        Console.WriteLine(string.Join(",", arr2));
    }
}

Khai báo HashSet:

var h = new HashSet<string>(arr1);

Loại bỏ trùng lặp:

string[] arr2 = h.ToArray();