溫馨提示×

c#集合怎樣避免重復

c#
小樊
148
2024-11-20 13:14:37
欄目: 編程語言

在C#中,集合默認情況下可能會包含重復的元素。為了避免這種情況,您可以使用以下幾種方法:

  1. 使用HashSet類:HashSet類是一個無序且不包含重復元素的集合。要使用HashSet,請從System.Collections.Generic命名空間中添加引用。
using System.Collections.Generic;

List<int> numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 6, 7 };
HashSet<int> uniqueNumbers = new HashSet<int>(numbers);
  1. 使用Dictionary類:Dictionary類是一個鍵值對集合,它不允許重復的鍵。您可以將集合中的元素作為鍵添加到字典中。
using System.Collections.Generic;

List<int> numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 6, 7 };
Dictionary<int, bool> uniqueNumbers = new Dictionary<int, bool>();

foreach (int number in numbers)
{
    uniqueNumbers[number] = true;
}
  1. 使用LINQ的Distinct方法:如果您使用的是IEnumerable集合,可以使用LINQ的Distinct方法來去除重復元素。
using System.Collections.Generic;
using System.Linq;

List<int> numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 6, 7 };
List<int> uniqueNumbers = numbers.Distinct().ToList();

請注意,以上方法可能會更改元素的順序。如果您需要保持原始順序,可以使用以下方法:

  1. 使用SortedSet類:SortedSet類是一個有序且不包含重復元素的集合。要使用SortedSet,請從System.Collections.Generic命名空間中添加引用。
using System.Collections.Generic;

List<int> numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 6, 7 };
SortedSet<int> uniqueNumbers = new SortedSet<int>(numbers);
  1. 使用OrderedDictionary類:OrderedDictionary類是一個有序字典,它不允許重復的鍵。您可以將集合中的元素作為鍵添加到OrderedDictionary中。
using System.Collections.Generic;

List<int> numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 6, 7 };
OrderedDictionary uniqueNumbers = new OrderedDictionary();

foreach (int number in numbers)
{
    uniqueNumbers[number] = true;
}

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