Reputation: 357
I have a list of objects containing 2 properties (id and letter). There can be exactly 4 different letter values for these objects (a, b, c and d). When I sort these objects, first I want to sort by letter. Then I would like to sort by id. When I sort by letter, I want the order to be a, b, d, c. I'm having trouble getting this custom sorting. When using linq, I tried something like this:
ListOfObjects.OrderBy(t => t.letter).ThenBy(t => t.letter.StartsWith("c") ? 2 : 1).ThenBy(t => t.id);
My thinking behind this was that you could simply move the objects where the letter starts with c down to the bottom of the list. However, this doesn't seem to work. Do you guys have any ideas? Any help would be greatly appreciated.
Upvotes: 2
Views: 1180
Reputation: 388253
You can create a mapping that translates the letters into a total order:
Dictionary<char, int> mapping = new Dictionary<char, int>()
{
{ 'a', 1 },
{ 'b', 2 },
{ 'd', 3 },
{ 'c', 4 }
};
listOfObjects.OrderBy(t => mapping[t.letter[0]]).ThenBy(t => t.id);
This has the benefit that it gives you absolute control over the order of those characters, and you can change the order externally, without having to change the actual order logic to handle exceptions.
Upvotes: 3
Reputation: 152624
Just reverse your first two conditions:
ListOfObjects.OrderBy(t => t.letter.StartsWith("c") ? 2 : 1)
.ThenBy(t => t.letter)
.ThenBy(t => t.id);
The first condition moves all c
s to the end, then sorts by letter
, then by id
.
Since your first condition was already sorting by letter
, trying to sort again based on letter had no effect.
Upvotes: 5