阅读量:2
在C#中,集合默认情况下可能会包含重复的元素。为了避免这种情况,您可以使用以下几种方法:
- 使用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);
- 使用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;
}
- 使用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();
请注意,以上方法可能会更改元素的顺序。如果您需要保持原始顺序,可以使用以下方法:
- 使用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);
- 使用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;
}
以上就是关于“c#集合怎样避免重复”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm