C# Array Sort(TKey[], TValue[], Int32, Int32, IComparer)
Description
Array Sort(TKey[], TValue[], Int32, Int32,
IComparer)
sorts a range of elements in
a pair of Array objects (one contains the keys and the other contains the corresponding
items) based on the keys in the first Array using the specified IComparer
Syntax
Array.Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
has the following syntax.
public static void Sort<TKey, TValue>(
TKey[] keys,/*from w ww . j a va 2s . c om*/
TValue[] items,
int index,
int length,
IComparer<TKey> comparer
)
Parameters
Array.Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
has the following parameters.
TKey
- The type of the elements of the key array.TValue
- The type of the elements of the items array.keys
- The one-dimensional, zero-based Array that contains the keys to sort.items
- The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.index
- The starting index of the range to sort.length
- The number of elements in the range to sort.comparer
- The IComparer generic interface implementation to use when comparing elements, or null to use the IComparable generic interface implementation of each element.
Returns
Array.Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
method returns
Example
using System;/*from w w w . ja v a 2s . c o m*/
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] myValues = {"40", "5", "3", "22", "1", "18" };
int[] myValuesizes = { 40, 5, 3, 22, 1, 18 };
Array.Sort(myValues, myValuesizes);
ReverseComparer rc = new ReverseComparer();
Array.Sort(myValues, myValuesizes, rc);
Array.Sort(myValues, myValuesizes, 3, 3);
Array.Sort(myValues, myValuesizes, 3, 3, rc);
}
}
The code above generates the following result.