mrNobody
mrNobody

Reputation: 91

Sorting lists in c#

I have two lists in C#.

public List<MyClass> objectList = new List<MyClass>(); // it is filled with MyClass objects

public List<int> numberList = new List<int>(); // it is filled with numbers

The index of numbers in the numberList correspond to object index in the objectList: For example: objectList[0] = o1 and numberList[0] = 3 ; objectList[1] = o2 and numberList[1] = 5 ...

objectList:             |o1 | o2 | o3 | o4 | o5 | ...
numberList:              3     5    6    1    4 ...

I want to sort the numbers in the numberList in ascending order and I want for the objetcs in objectList to move with them: After sorting:

objectList:             |o4 | o1 | o5 | o2 | o3 | ...
numberList:              1     3    4    5    6 ...

In practical use I need this for implementing the Hill climbing algorithm on a N queen problem. In the objectList I store positions of all the queens on the board and in the numberList I store the calculated heuristics for the positions. Then I want to sort the numberList so I get the position with the lowest heuristic value. The goal is to move to the position with the lowest heuristic value.

Upvotes: 1

Views: 349

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660523

Transform your object list into a sequence of items paired with their indices:

var pairs = objectList.Select(item, index) => new { item, index };

Now you have something you can use to do an ordering:

var orderedPairs = pairs.OrderBy(pair => numberList[pair.index]);

Now you have an ordered list of pairs. Turn that back into an ordered list of items:

var ordered = orderedPairs.Select(pair => pair.item);

and turn it into a list:

var orderedList = ordered.ToList();

Note that your original lists are not altered. This creates a new list that is in the order you want.

Of course you can do it all in one expression if you like:

objectList = objectList
  .Select((item, index) => new { item, index } )
  .OrderBy(pair => numberList[pair.index])
  .Select(pair => pair.item)
  .ToList();

Now, all that said: it sounds like you're doing too much work here because you've chosen the wrong data structure. It sounds to me like your problem needs a min heap implementation of a priority queue, not a pair of lists. Is there some reason why you're not using a priority queue?

Upvotes: 7

Related Questions