2

I got an array which contains items of the object 'Person'

IS

I need to have the special people on top (those sorted by Id) and the nonspecial people below (those sorted alphabetically). It should look like this:

SHOULD

Is there a way of sorting it like this without having to split the list, sort it individually and then merging it back together?

1

2 Answers 2

7

First you can OrderBy by Special (note that false < true) and then you can use condition within ThenBy like this:

var result = persons
  .OrderBy(person => person.Special != "Yes")
  .ThenBy(person => person.Special == "Yes" ? person.Id : 0)
  .ThenBy(person => person.Special == "Yes" ? "" : person.Name);
Sign up to request clarification or add additional context in comments.

1 Comment

I like the conditional sorting since i imagine that true is "higher" than false. But for all others i would make it more explicit: persons.OrderBy(p => p.Special == "Yes" ? 0 : 1)...
0

A non-linq version:

list.Sort((a, b) =>
{
    if (a.Special != b.Special)
    {
        return a.Special ? -1 : 1;
    }

    return a.Name.CompareTo(b.Name);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.