• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

230
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?

about 3 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);
about 3 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);
});
about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error