在C#中以降序对数组进行排序的不同方法

``````Input : array = {5, 9, 1, 4, 6, 8};
Output : 9, 8, 6, 5, 4, 1

Input : array = {1, 9, 6, 7, 5, 9};
Output : 9 9 7 6 5 1

Input : array = {-8, 9, 7, 7, 0, 9, -9};
Output : 9 9 7 7 0 -8 -9``````

``````//C# program sort an array in decreasing order
//using Array.Sort() and Array.Reverse() Method
using System;

class GFG {

//Main Method
public static void Main()
{

//declaring and initializing the array
int [] arr = new int [] {1, 9, 6, 7, 5, 9};

//Sort array in ascending order.
Array.Sort(arr);

//reverse array
Array.Reverse(arr);

//print all element of array
foreach ( int value in arr)
{
Console.Write(value + " " );
}
}
}``````

``9 9 7 6 5 1``

``````//C# program sort an array in
//decreasing order using
//CompareTo() Method
using System;

class GFG {

//Main Method
public static void Main()
{

//declaring and initializing the array
int [] arr = new int [] {1, 9, 6, 7, 5, 9};

//Sort the arr from last to first.
//compare every element to each other
Array.Sort<int>(arr, new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)));

//print all element of array
foreach ( int value in arr)
{
Console.Write(value + " " );
}
}
}``````

``9 9 7 6 5 1``

``````//C# program sort an array
//in decreasing order
using System;

class GFG {

//Main Method
public static void Main()
{

//declaring and initializing the array
int [] arr = new int [] {1, 9, 6, 7, 5, 9};

//Sort the arr from last to first
//Normal compare is m-n
Array.Sort<int>(arr, delegate ( int m, int n)
{ return n - m; });

//print all element of array
foreach ( int value in arr)
{
Console.Write(value + " " );
}
}
}``````

``9 9 7 6 5 1``

``````//C# program sort an array
//in decreasing order using
//iterative way
using System;

class GFG {

//Main Method
public static void Main()
{
//declaring and initializing the array
int [] arr = new int [] {1, 9, 6, 7, 5, 9};

int temp;

//traverse 0 to array length
for ( int i = 0; i <arr.Length - 1; i++)

//traverse i+1 to array length
for ( int j = i + 1; j <arr.Length; j++)

//compare array element with
//all next element
if (arr[i] <arr[j]) {

temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

//print all element of array
foreach ( int value in arr)
{
Console.Write(value + " " );
}
}
}``````

``9 9 7 6 5 1``

LINQ代表语言集成查询。它是一种统一的查询语法，用于检索和保存来自不同来源的数据。这里，使用orderby降序排序方法进行降序排序。LINQ返回IOrderedIEnumerable，使用ToArray()方法将其转换为Array。

``````//C# program sort an array in decreasing
//order by using LINQ OrderByDescending
//method
using System;
using System.Linq;

class GFG {

//Main Method
public static void Main()
{

//declaring and initializing the
//array with 6 positive number
int [] arr = new int [] {1, 9, 6, 7, 5, 9};

//Sort the arr in decreasing order
//and return a array
arr = arr.OrderByDescending(c => c).ToArray();

//print all element of array
foreach ( int value in arr)
{
Console.Write(value + " " );
}
}
}``````

``9 9 7 6 5 1``