0

I have aList<XYZ>, let's call itoListXYZ.

{{3,2,1},{6,5,4},{9,8,7}}

and aList<double>we'll calloListD.

{9,2,5}

Both lists are related, i.eoListD[i]corresponds tooListXYZ[i].I need to sort theXYZvalues inoListXYZaccording to their correspondingdoublevalues inoListD, like so:

{2,5,9} {{6,5,4},{9,8,7},{3,2,1}}

UsingoListD.Sortgives the desired order, but i need a way to sortoListXYZfollowing said order.

I have tried with LINQ or the solution described here, but haven't found the desired results yet.

3
  • I don't understand the question @_@. Commented Feb 6, 2020 at 8:53
  • what is their 'corresponding double value'? I dont think you've given enough info here for us to help Commented Feb 6, 2020 at 8:53
  • Can you post some tests case (i.e. a list of inputs/outputs)? Commented Feb 6, 2020 at 8:57

1 Answer 1

4

Use Enumerable.Zip to combine them, then OrderBy to order

Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

var list = new List<(int, int, int)>(){(3, 2, 1),(6, 5, 4),(9, 8, 7)}; var doubles = new List<double>(){9,2,5}; var results = list.Zip(doubles, (tuple, d) => (t: tuple, d: d)) .OrderBy(x => x.d) .Select(x => x.t); foreach (var result in results) Console.WriteLine(result); 

Output

(6, 5, 4) (9, 8, 7) (3, 2, 1) 
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer is superb - it's easily better than the ones in the duplicate question - I'd suggest you go and post yours there too (with a bit of tweaking).
Exactly the kind of solution i was looking for. Simple and to the point. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.