使用HashSet<>去除重复元素的集合

比如,某一个阵列中,有重复的元素,我们想去除重复的,保留一个。
HashSet<T>含不重复项的无序列表,从MSDN网上了解到,这集合基于散列值,插入元素的操作非常快。

你可以写一个方法:

 class Bn
    {
        public string[] Data { get; set; }
        public string[] RemoveDuplicatesElement()
        {
            HashSet<string> hashSet = new HashSet<string>(Data);
            string[] result = new string[hashSet.Count];
            hashSet.CopyTo(result);
            return result;
        }
    }
Source Code

接下来,在控制台测试上面的方法:

 class Program
    {
        static void Main(string[] args)
        {
            Bn obj = new Bn();
            obj.Data =  new[] { "F", "D", "F", "E", "Q","Q", "D" };
            var result = obj.RemoveDuplicatesElement();

            for (int i = 0; i < result.Length; i++)
            {
                Console.WriteLine(result[i]);
            }

            Console.ReadLine();
        }
    }
Source Code
原文地址:https://www.cnblogs.com/insus/p/8136522.html