Home > Software design >  C# Sort Array by multiple different conditions
C# Sort Array by multiple different conditions

Time:03-16

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?

CodePudding user response:

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);

CodePudding user response:

A non-linq version:

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

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