简体   繁体   中英

C# array.sort() for multiple arrays in Descending order

I Have two arrays named weights and values. I wanted to sort Values based on the sorting of Weights. That works perfectly fine by doing

Array.Sort(Weights,Values);

This gives me arrays sorted in ascending order. I wanted to do the same sorting in Descending order. Is there a better way to do without using Array.Reverse(Weights) and Array.Reverse(Values)

You'll have to use this overload and provide a custom IComparer<T> . The relatively new Comparer<T>.Create method makes this a lot easier because you can simply turn a delegate or lambda expression into an IComparer<T> without having to code a full implementation yourself. It's not clear from the question what the datatype of Weights and Values are, but here's an example using double[] and int[] respectively:

var Weights = new [] { 1.7, 2.4, 9.1, 2.1, };
var Values = new [] { 7, 9, 5, 3, };

Array.Sort(Weights, Values, Comparer<double>.Create((x, y) => y.CompareTo(x)));

And just for fun, here's a solution using LINQ:

var pairs = Weights.Zip(Values, Tuple.Create);
var orderedPairs = pairs.OrderByDescending(x => x.Item1);

I'd also recommend that you consider using a class to store weights and values together rather than as two separate arrays.

First, create a structure that holds the corresponding items.

var items =
    Weights
        .Select((weight, index) =>
            new
            {
                Weight = weight,
                Value = Values[index]
            }
        )
        .OrderByDescending(item => item.Weight)
        .ToArray();

Then you can get the sorted array back:

Weights = items.Select(item => item.Weight).ToArray();
Values = items.Select(item => item.Value).ToArray();

But you may also try one of the answers here:
Better way to sort array in descending order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM