在好例子网,分享、交流、成长!
<<

C# 数组去重方法

using System;
using System.Linq;
class Program
{
    static void Main()
    {
	int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
	int[] distinctArr = arr.Distinct().ToArray();
        
        foreach (int num in distinctArr)
        {
            Console.WriteLine(num);
        }
    }
}

这里的 arr 是原始数组,distinctArr 则是去重后的数组。可以看到,Distinct() 方法会返回一个 IEnumerable 类型的序列,我们可以通过 ToArray() 方法将其转换为数组。

除了使用 Linq 的 Distinct() 方法外,还可以使用其他方法来实现 C# 数组去重。下面给出几种常用的方法,并提供完整可运行示例代码:

  1. 使用 HashSet 来去重:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
        
        HashSet<int> set = new HashSet<int>(arr);
        int[] distinctArr = new int[set.Count];
        set.CopyTo(distinctArr);
        
        foreach (int num in distinctArr)
        {
            Console.WriteLine(num);
        }
    }
}
  1. 使用 Dictionary 来去重:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
        
        Dictionary<int, bool> dict = new Dictionary<int, bool>();
        foreach (int num in arr)
        {
            if (!dict.ContainsKey(num))
            {
                dict[num] = true;
            }
        }
        
        int[] distinctArr = new int[dict.Keys.Count];
        dict.Keys.CopyTo(distinctArr, 0);
        
        foreach (int num in distinctArr)
        {
            Console.WriteLine(num);
        }
    }
}

以上是两种常用的 C# 数组去重方法,每种方法都有相应的完整可运行示例代码。你可以根据自己的需求选择合适的方法来去除数组中的重复元素。

标签: 去重 方法 数组 C#

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

报警