C#数组去重的几种方法

在C#中,有多种方法可以去除数组中的重复元素,以下是一些常见的方式:

  1. 使用HashSet:
int[] arr = { 1, 2, 3, 2, 1, 5, 6, 5 };
HashSet<int> hashSet = new HashSet<int>(arr);
arr = hashSet.ToArray();

HashSet是一个不包含重复元素的集合,通过将数组转换为HashSet,然后再次转换回数组,可以实现去重。

  1. 使用LINQ(Language Integrated Query):
int[] arr = { 1, 2, 3, 2, 1, 5, 6, 5 };
arr = arr.Distinct().ToArray();

LINQ的Distinct()方法可以去除数组中的重复元素。

  1. 使用List和循环:
int[] arr = { 1, 2, 3, 2, 1, 5, 6, 5 };
List<int> list = new List<int>(arr);
list = list.Distinct().ToList();
arr = list.ToArray();

首先将数组转换为List,然后使用List的Distinct方法去重,最后转换回数组。

以上三种方法中,HashSet和LINQ的方式较为简洁高效,适用于大部分情况。

还可以利用for循环

int[] array = {1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9};
List<int> uniqueList = new List<int>();

for(int i = 0; i < array.Length; i++)
{
    if(!uniqueList.Contains(array[i]))
    {
        uniqueList.Add(array[i]);
    }
}

// Convert List back to array
int[] uniqueArray = uniqueList.ToArray();
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值