C# Soft Number By Difference From Input

I have the following code. Please help me get my desired output. I have a list of numbers then I have input value which is 4. I want that my list will be sorted based on 0 difference first then the rest will be ascending. For example in my list there are 4s. My input is 4 so I want to sort those numbers where number item – input value=0 (4-4=0).

C#

    static void Main(string[] args)
    {
        var numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 7, 4, 8, 1, 4 };
        var sortedNumbers = numbers.OrderBy(x => x - 4 == 0);
        foreach (var item in sortedNumbers)
        {
            Console.WriteLine(item);
        }
        Console.ReadLine();
    }

OUTPUT

1
2
3
5
6
7
8
1
4
4
4
4

Desired Output

4
4
4
4
1
1
2
3
5
6
7
8

Answer

You can achieve your desired output by using a ternary expression inside the OrderBy lambda :

    static void Main(string[] args)
    {
        var numbers = new List<int> { 1, 2, 3, 4, 4, 5, 6, 7, 4, 8, 1, 4 };
        var sortedNumbers = numbers.OrderBy(x => x==4? int.MinValue: x);
        foreach (var item in sortedNumbers)
        {
            Console.WriteLine(item);
        }
        Console.ReadLine();
    }       

output :

4
4
4
4
1
1
2
3
5
6
7
8

Edit : in case you have zero or negative number in your list, your number will be order as follow : first, exact match, then ascending. For example : { -1, 0, 0, -12, 1, 2, 3, 4, 4, 5, 6, 7, 4, 8, 1, 4 }

the result will be the following :

4
4
4
4
-12
-1
0
0
1
1
2
3
5
6
7
8

Leave a Reply

Your email address will not be published. Required fields are marked *