int[] OrderedListToFollow = {1,2,4,5}
int[] ListB = {2,3,4,8,9}
Based on the two lists above I need to sort ListB based on the order defined in OrderedListToFollow. Since 3,8,9 are not part of the OrderedListToFollow those can appear in any order, so the acceptable solutions could have any of the following :
int[] ListB = {2,4,3,8,9}
int[] ListB = {2,4,8,3,9}
int[] ListB = {2,4,9,3,8}
I tried doing this as follows but it does not order it :
ListB = ListB.OrderBy(id => OrderedListToFollow.ToList().IndexOf(id)).ToArray();
EDIT
The order above works but it places the items not present in OrderedListToFollow first and then the remaining.
As noted, it was already working apart from putting the results at the beginning. To fix this, I'd add an extension method:
public static int IndexOfOrMax(this IEnumerable<T> source, T item)
{
int index = source.IndexOf(item);
return index == -1 ? int.MaxValue : index;
}
Also note that you don't need to call ToList
on OrderedListToFollow
- currently you're calling that a lot, which is very inefficient. With the above extension method in place, you can use:
int[] orderedListToFollow = {1,2,4,5};
int[] listB = {2,3,4,8,9};
listB = listB.OrderBy(id => orderedListToFollow.IndexOfOrMax(id)).ToArray();
See more on this question at Stackoverflow