none
Sort Array with lambda expression in C# RRS feed

  • Question

  • Hello,

    Why have I an error in my code?

    Thanks

            static void Main(string[] args)
            {
                int[] myArray = { 1,100 , 3, 5, 12, 53, 6, 7 };
                int a[];
                a = Array.Sort(myArray, (x, y) => x.CompareTo(y));
    
    
                for (int i = 0; i < a.Length; i++)
                {
                    Console.WriteLine(a[i]);
                }
    
                Console.ReadKey();
            }

    Saturday, December 16, 2017 1:48 PM

Answers

  • Two errors:

    - The declaration int a[] should be int[] a.

    - The Array.Sort method sorts the array "in place". It doesn't return an array. So you can't assign it back to a.

    Array.Sort(myArray, (x, y) => x.CompareTo(y));

    • Marked as answer by Arash_89 Saturday, December 16, 2017 2:17 PM
    Saturday, December 16, 2017 2:00 PM
    Moderator
  • For a descending sort, instead of (x, y) => x.CompareTo(y) you can use either of the following:

    (x, y) => - x.CompareTo(y)

    (x, y) => y.CompareTo(x)

    (y, x) => x.CompareTo(y)

    • Marked as answer by Arash_89 Saturday, December 16, 2017 6:28 PM
    Saturday, December 16, 2017 4:59 PM
    Moderator

All replies

  • Two errors:

    - The declaration int a[] should be int[] a.

    - The Array.Sort method sorts the array "in place". It doesn't return an array. So you can't assign it back to a.

    Array.Sort(myArray, (x, y) => x.CompareTo(y));

    • Marked as answer by Arash_89 Saturday, December 16, 2017 2:17 PM
    Saturday, December 16, 2017 2:00 PM
    Moderator
  • Thanks Alberto, Now if I want descending sort with that syntax, What I do? 

    Saturday, December 16, 2017 2:19 PM
  • For a descending sort, instead of (x, y) => x.CompareTo(y) you can use either of the following:

    (x, y) => - x.CompareTo(y)

    (x, y) => y.CompareTo(x)

    (y, x) => x.CompareTo(y)

    • Marked as answer by Arash_89 Saturday, December 16, 2017 6:28 PM
    Saturday, December 16, 2017 4:59 PM
    Moderator
  • var MyArray = new [] { 3, 4, 6, 1, 3, 5, 9, 23 };            
    Array.Sort(MyArray, (x, y) => y - x);
    MessageBox.Show(String.Join(",", MyArray));
    Console.WriteLine(String.Join(",",MyArray));

    More simple... Have in mind Sort Method is void there is not need to create a new Array because MyArray was updated with the Sort Method.

    Friday, June 22, 2018 7:31 AM