Sort int array s

Keywords: C#

Learn some more C#basics today, such as sorting Int Array:

You can create a category, its properties, and two constructors in the console application:

 

 class Af
    {
        private int[] myVar;

        public int[] MyIntArray
        {
            get { return myVar; }
            set { myVar = value; }
        }

        public Af()
        {

        }

        public Af(int[] arr)
        {
            this.myVar = arr;
        }
        
    }
Source Code

 

Next, I'll add to this category how we process data:
If we need to output the result on the screen:



 private void Output(int[] sortResult)
        {
            foreach (var i in sortResult)
            {
                Console.WriteLine(i);
            }
        }

        private void Output(IOrderedEnumerable<int> sortResult)
        {
            foreach (var i in sortResult)
            {
                Console.WriteLine(i);
            }
        }
Source Code


Sort() can be used to sort arrays:


 public void SortAsc()
        {
            Array.Sort(myVar);
            Output(myVar);
        }
Source Code

 

Now we can go to the console to test the code written above:


What if we need to sort the output in reverse order?You can use the Reverse() method, that is, Sort() followed by Reverse() to reverse the order:

 public void SortDesc()
        {
            Array.Sort(myVar);
            Array.Reverse(myVar);
            Output(myVar);
        }
Source Code

 
Now let's go to the console and see how the code looks:



At this point, the original function has been implemented, but Insus.NET Here, you want to use another way to accomplish this same function:


 public void ArrayOrderBy()
        {
            var result = myVar.OrderBy(g => g);
            Output(result);
        }

        public void ArrayOrderByDescending()
        {
            var result = myVar.OrderByDescending(g => g);
            Output(result);
        }
Source Code

 

Run result:

Posted by alant on Tue, 07 Jul 2020 07:53:10 -0700