Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Sort Array by multiple different conditions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading