在C#中,集合默認情況下可能會包含重復的元素。為了避免這種情況,您可以使用以下幾種方法:
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);
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;
}
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();
請注意,以上方法可能會更改元素的順序。如果您需要保持原始順序,可以使用以下方法:
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);
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;
}