Reputation: 357
How do I re-arrange Array X, based on the size of corresponding values in Array Y.
Here's what I mean in pseudo code:
Array X = Red, Yellow, Green, Blue
Array Y = 68.4, 42.3, 53.6, 69.3 (random positive doubles)
I want an output of:
Array Z = Blue, Red, Green, Yellow
i.e. The it ranks the elements of Array Y by size (and so it goes to 69.4, 68.3, 53.6, 42.3), and then applies that same re-ordering to the elements of Array X, re ordering it to Blue, Red, Green, Yellow
My attempt so far is creating a list that adds the elements, re-orders them using the list.sort method, but its a complete mess to be honest because I can't get my head round the logic required.
EDIT - using doubles instead of ints
Upvotes: 1
Views: 93
Reputation: 116108
List<string> colors = new List<string>() { "Red", "Yellow", "Green", "Blue" };
List<double> order = new List<double>() { 68.4, 42.3, 53.6, 69.3 };
var newList = order.Select((item, inx) => new { item, inx })
.OrderByDescending(x => x.item)
.Select(x => colors[x.inx])
.ToList();
Upvotes: 1
Reputation: 6683
Using a list of key-value pairs you would get better results, then you could simply sort by the values and output an array or list of the keys.
Something like the Compare2 method in this article is what you are looking for: http://www.dotnetperls.com/sort-keyvaluepair
Upvotes: 0
Reputation: 32481
This may helps:
List<Tuple<string, int>> values = new List<Tuple<string, int>>();
values.Add(new Tuple<string, int>("Red", 68));
values.Add(new Tuple<string, int>("Yellow", 42));
values.Add(new Tuple<string, int>("Green", 53));
var sortedValues = values.OrderByDescending(i => i.Item2).ToList();
Upvotes: 0
Reputation: 203823
There is an overload of Array.Sort
specifically for this.
Just use:
Array.Sort(Y, X);
Having said that, while you can do this, I would strongly suggest that you create a single array of some composite item, having both a Color
and a int
value, and then sort it based on the int, rather than having two different arrays in which the index of each array corresponds to one component of "something". It will make dealing with it easier.
Upvotes: 4