溫馨提示×

c# set集合如何去重元素

c#
小樊
106
2024-11-16 15:31:45
欄目: 編程語言

在C#中,可以使用HashSet類來存儲不重復的元素。HashSet是基于哈希表實現的,因此它會自動去除重復元素。以下是如何使用HashSet來去重元素的示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 創建一個包含重復元素的List
        List<int> listWithDuplicates = new List<int> { 1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9 };

        // 使用HashSet去重
        HashSet<int> set = new HashSet<int>(listWithDuplicates);

        // 將HashSet轉換為List并輸出結果
        List<int> uniqueList = new List<int>(set);
        Console.WriteLine("Unique elements:");
        foreach (int item in uniqueList)
        {
            Console.WriteLine(item);
        }
    }
}

在這個示例中,我們首先創建了一個包含重復元素的List。然后,我們使用HashSet來存儲這些元素,HashSet會自動去除重復元素。最后,我們將HashSet轉換為List并輸出結果。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女