溫馨提示×

如何處理C# Vector中的重復元素

c#
小樊
88
2024-09-04 16:24:43
欄目: 編程語言

在C#中,Vector<T> 類型通常用于表示多維向量,而不是存儲一系列元素的集合

以下是使用HashSet刪除重復元素的示例:

using System;
using System.Collections.Generic;
using System.Numerics;

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

        // 將Vector<int>轉換為List<int>
        List<int> listWithDuplicates = new List<int>(vectorWithDuplicates);

        // 使用HashSet刪除重復元素
        HashSet<int> hashSet = new HashSet<int>(listWithDuplicates);

        // 將HashSet轉換回List<int>
        List<int> uniqueList = new List<int>(hashSet);

        // 輸出去重后的結果
        Console.WriteLine("Unique elements:");
        foreach (int element in uniqueList)
        {
            Console.WriteLine(element);
        }
    }
}

這段代碼首先創建了一個包含重復元素的 Vector<int>。然后,它將 Vector<int> 轉換為 List<int>,接著使用 HashSet<int> 刪除重復元素。最后,將 HashSet<int> 轉換回 List<int> 并輸出去重后的結果。

請注意,此示例僅適用于整數類型的向量。對于其他類型,只需相應地更改 Vector<T>、List<T>HashSet<T> 中的泛型參數即可。

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