C#如何给整型数组去重?如何排序?

C#中独特的数组语法真的让我感到脑阔疼。。
记录一下这奇怪的用法,数组泛型list搭配食用更佳哦~

数组的去重:

先将数组num转换成泛型list,再使用泛型方法Distinct()去重

 List<int> list = num.ToList(); 
 List<int> newList = list.Distinct().ToList(); //返回去重后的list

数组排序

数组排序只需要使用Array.Sort()方法即可,默认是升序

 Array.Sort(newArr);//排序,升序

若想降序排序,当然可以,只需要加一行代码就可以实现,代码如下:

Array.Reverse(nums);//反转

下面是一道水题,使用了数组去重和排序的方法
明明的随机数

使用C#实现:

using System;
using System.Collections.Generic;
using System.Linq;

namespace DI1026sort
{
   
    class Program
    {
   
        static void Main(string[] args)
        {
   
            int n = int.Parse(Console.ReadLine());
            var str = Console.ReadLine().Split(' ');
            int[] num = new int[n];
            for(var i = 0; i < n; i++)
            {
   
                num[i] = Convert.ToInt32(str[i].ToString());
            }
            List<int> list = num.ToList();
            List<int> newList = list.Distinct().ToList();
            int[] newArr = newList.ToArray();
            Array.Sort(newArr);
            Console.WriteLine(newArr.Length);
            for(var i = 0; i < newArr.Length; i++)
            {
   
                Console.Write("{0} ",newArr[i]);
            }
            //Console.ReadKey();
        }
    }
}