hakuna
hakuna

Reputation: 6701

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)

Upvotes: 3

Views: 3581

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149108

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.

Upvotes: 5

Gabor
Gabor

Reputation: 3256

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

Upvotes: 2

Related Questions