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

Linq OrderByDescending after that ThenByDescending in C#

I have list of integer and I am trying to sort this based on first in descending order and after that I want to sort with in two list based on even and odds but still in descending order like this

using System;
using System.Linq;
using System.Collections.Generic;
                
public class Program
{
    public static void Main()
    {
        var numbers = new List<int>() { 3, 7, 1, 5, 4, 6, 2 };
        var sortedDescendingNumbers = numbers.OrderByDescending(x => x);
        var sortedNumbers = sortedDescendingNumbers.ThenByDescending(x => x % 2 == 0);

        foreach (var num in sortedNumbers)
        {
            Console.Write(num + " ");
        }
    }
}

but this one print the result as 7 6 5 4 3 2 1 and I am expecting output like 7 5 3 1 6 4 2

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

>Solution :

Your first block of numbers should be the odd ones, so you have to order by divisibility by 2 first and then by descending value.

var sortedOddEvenNumbers = numbers.OrderBy(x => x % 2 == 0);
var sortedNumbers = sortedOddEvenNumbers.ThenByDescending(x => x);
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