0

I have two list of object like this:

List<Result> result = [{id: 1, country: 'France'}, {id: 2,country: 'Sweden'}, {id: 5,country: 'Denmark'}]

List<OrderResult> orderResult = [{id: 5, score: 12}, {id: 1, score: 11}, {id: 2, score 10}]

I would order the list result based on the order of the array orderResult to obtain this final result:

result = [{id: 5, country 'Denmark'}, {id: 1, country: 'France'}, {id: 2, country: 'Sweden'}]
Rob None
  • 479
  • 2
  • 9
  • 22
  • this may help you: https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object – Benji Aug 02 '21 at 07:06
  • 1
    Unfortunatly this does not help in my case, because I don't need to order for a property inside the first list. – Rob None Aug 02 '21 at 07:08
  • Why did you provide SQL tag? If this data comes from a data base, then why not let that one do the work? `SELECT t1.id, t1.country FROM firstTable t1 JOIN secondTable t2 ON t1.id = t2.id ORDER BY t2.score` – Aconcagua Aug 02 '21 at 07:20
  • Just as idea: If both lists have exactly the same ids as elements and you receive both lists ordered by id – which is not (yet?) the case in your example – you might simply sort the second list and do all the same steps in parallel on first one, too. – Aconcagua Aug 02 '21 at 07:35

1 Answers1

3

You could transform the OrderResult list into a dictionary with the id as key and index as value:

 var orderDict = orderResults
            .Select((value, index) => (value.Id, index))
            .ToDictionary(p => p.Id, p => p.index);

Then it should be trivial to order the results, assuming all results have a corresponding entry in the orderResults.:

result.OrderBy(r => orderDict[r.id]);
JonasH
  • 28,608
  • 2
  • 10
  • 23