Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ method to sort a list based on a bigger list

Tags:

c#

sorting

linq

List<int> _lstNeedToOrder = new List<int>();
_lstNeedToOrder.AddRange(new int[] { 1, 5, 6, 8 });

//I need to sort this based on the below list.

List<int> _lstOrdered = new List<int>();//to order by this list
_lstOrdered.AddRange(new int[] { 13, 5, 11, 1, 4, 9, 2, 7, 12, 10, 3, 8, 6 });

order will be -->_lstNeedToOrder = 5,1,8,6

How can I do it?

like image 713
Rami Alshareef Avatar asked Aug 04 '13 07:08

Rami Alshareef


2 Answers

Well the simple - but inefficient - way would be:

var result = _lstNeedToOrder.OrderBy(x => _lstOrdered.IndexOf(x));

An alternative would be to work out a far way of obtaining the desired index of a value. If your values will always in be the range [1...n] you could just invert that "ordered" list to be a "list of indexes by value". At which point you could use:

var result = _lstNeedToOrder.OrderBy(x => indexes[x]);

(where indexes would have an extra value at the start for 0, just to make things simpler).

Alternatively, you could create a Dictionary<int, int> from value to index. That would be more general, in that it would handle a very wide range of values without taking a lot of memory. But a dictionary lookup is obviously less efficient than an array or list lookup.

Just as a side note which wouldn't format well as a comment, your initialization can be simplified using a collection initializer:

var listToOrder = new List<int> { 1, 5, 6, 8 };
var orderedList = new List<int> { 13, 5, 11, 1, 4, 9, 2, 7, 12, 10, 3, 8, 6 };
like image 177
Jon Skeet Avatar answered Oct 28 '22 19:10

Jon Skeet


    List<int> results = _lstOrdered.Where(item => _lstNeedToOrder.Contains(item)).ToList();
like image 44
Vaughan Hilts Avatar answered Oct 28 '22 19:10

Vaughan Hilts