在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;
}