Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
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:

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report

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);
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!