I came across this problem at work, and though I have a solution, I can’t help feeling there is a more elegant way. The use of List.IndexOf() stands out as a bit hacky to me.
I have to sort a collection of BreakdownItems by credit rating. Credit ratings don’t follow alphabetical order so I’ve treated them as just having some arbitrary, non logical order.
IEnumerable<BreakdownItem> unsortedCreditRatings = new List<BreakdownItem>
{
new BreakdownItem{ Name = "CCC", Weight=20d},
new BreakdownItem{ Name = "AA", Weight=20d},
new BreakdownItem{ Name = "AAA", Weight=10d},
new BreakdownItem{ Name = "B", Weight=50d},
};
var sortOrder = new List<string>
{ "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "below CCC" };
var sortedRatingBreakdown = unsortedCreditRatings
.OrderBy(item => sortOrder.IndexOf(item.Name));
Can you make the credit rating an enum instead of a string? You could then assign those enum values the correct sort order.