26

I have two lists { 7 3 5 } and {9 8 1}.

I want to sort my first list and I want the second list to have the same index permutation as given by the first list.

{3 5 7} => {8 1 9}

Is it possible to do this in a single LINQ statement?

2
  • 1
    So, to make sure I'm clear, you want to sort the first list, and have the second list sort by that key as well? Commented May 18, 2012 at 15:20
  • 1
    Darn it, Jon beat me to it... Zip is handy for that. Commented May 18, 2012 at 15:22

2 Answers 2

43

Sounds like you might want:

var list1 = new List<int> { 7, 3, 5 };
var list2 = new List<int> { 9, 8, 1 };

var orderedZip = list1.Zip(list2, (x, y) => new { x, y } )
                      .OrderBy(pair => pair.x)
                      .ToList();
list1 = orderedZip.Select(pair => pair.x).ToList();
list2 = orderedZip.Select(pair => pair.y).ToList();
Sign up to request clarification or add additional context in comments.

9 Comments

How is it possible to answer this question in 68 seconds?
@Aidan, Because he's Jon Skeet, 'nuff said... :-)
He's like the Chuck Norris of SO
@Aidan: Hah! Sounds like a good line of jokes... Jon Skeet doesn't need to sort lists, when Jon Skeet arrives they sort themselves.
It's an honor to be beaten to a response by Jon Skeet.
|
10

You could try using the Zip method:

var sortedPairs = list1
    .Zip(list2, (item1, item2) => new KeyValuePair<int, int>(item1, item2))
    .OrderBy(pair => pair.Key);

Then you could get the first sorted list by:

var sortedList1 = sortedPairs.Select(pair => pair.Key);

And the second list by:

var sortedList2 = sortedPairs.Select(pair => pair.Value);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.