Is there a way in Linq to do an OrderBy against a set of values (strings in this case) without knowing the order of the values?
Consider this data:
A
Not really efficient for large lists but fairly easy to read:
public class FixedOrderComparer : IComparer
{
private readonly T[] fixedOrderItems;
public FixedOrderComparer(params T[] fixedOrderItems)
{
this.fixedOrderItems = fixedOrderItems;
}
public int Compare(T x, T y)
{
var xIndex = Array.IndexOf(fixedOrderItems, x);
var yIndex = Array.IndexOf(fixedOrderItems, y);
xIndex = xIndex == -1 ? int.MaxValue : xIndex;
yIndex = yIndex == -1 ? int.MaxValue : yIndex;
return xIndex.CompareTo(yIndex);
}
}
Usage:
var orderedData = data.OrderBy(x => x, new FixedOrderComparer("A", "B", "C"));
Note: Array.IndexOf uses EqualityComparer to find the target index.