int[] intArray = new int[] { 3, 1, 4, 5, 2 };Of course, this is not efficient for large arrays.
Array.Sort<int>( intArray );
Array.Reverse( intArray );
A better approach is to create a custom Comparer. Following is a nice generics class that will sort an array in descending order. Note that the object type must be comparable (inherit from IComparable) as any useful class should.
Here’s a simple web application to test it:
<%@ Page Language="C#" AutoEventWireup="true" Codebehind="SortSample.aspx.cs" Inherits="SampleApplication.SortSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sort Ascending /Descending Order by Generic</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace SampleApplication.
{
public partial class SortSample: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
char[] charArray = new char[] { 'r', '1', 'f', 'c', 'x' };
string[] stringArray = new string[] { "array item 1", "array item 2", "array item 3", "array item 4", "array item 5" };
ArraySorter<int>.SortDescending(intArray);
ArraySorter<char>.SortDescending(charArray);
ArraySorter<string>.SortDescending(stringArray);
BindDropDownList(DropDownList1, intArray);
BindDropDownList(DropDownList2, charArray);
BindDropDownList(DropDownList3, stringArray);
}
private static void BindDropDownList(BaseDataBoundControl ddl, Array arr)
{
if(ddl !=null && arr !=null && arr.Length>0)
{
ddl.DataSource = arr;
ddl.DataBind();
}
}
static public class ArraySorter<T> where T : IComparable
{
static public void SortDescending(T[] array)
{
Array.Sort<T>(array, s_Comparer);
}
static private readonly ReverseComparer s_Comparer = new ReverseComparer();
private class ReverseComparer : IComparer<T>
{
public int Compare(T object1, T object2)
{
return -((IComparable)object1).CompareTo(object2);
}
}
}
}
}
I hope it will help you in someway.
Happy Coding!!!