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?
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 };
List<int> results = _lstOrdered.Where(item => _lstNeedToOrder.Contains(item)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With