Ive just written the following code, which will order strings by their native string.Compare()
but allow a collection of exceptions (in this case customPr
First, I think it's useful to restate the problem: You want to sort by:
That means you can achieve your sort order by using OrderBy()
for the first condition followed by ThenBy()
for the second one:
private static uint NegativeToMaxValue(int i)
{
if (i < 0)
return uint.MaxValue;
return (uint)i;
}
…
var ordered = unorderered
.OrderBy(a => NegativeToMaxValue(Array.IndexOf(new[] { "y", "x" }, a)))
.ThenBy(a => a);
NegativeToMaxValue()
is necessary, because items not in the array should be last, but they would be first normally, because the index is -1. (A hackish and unreadable way to do the same would be to directly cast the result of IndexOf()
to uint
.)
If you wanted to reuse this sorting by creating an IComparer
, I believe there is nothing in .Net to help you with that. But you could use ComparerExtensions instead:
IComparer comparer = KeyComparer
.OrderBy(a => NegativeToMaxValue(Array.IndexOf(new[] { "y", "x" }, a)))
.ThenBy(a => a);