How to get the second lowest number from a array in C#
Learn, how to get the second Lowest number from a array in C# with the help of examples.
Consider, we have a following array of numbers in our code.
int[] myArray = new int[] { 4, 24, 1, 20, 3, 40, 2 };
Now, we need to get the second Lowest 2
number from a above array in C#.
To get the second Lowest number from a array, first we need to sort the array using the Array.sort()
method then get the second Lowest number using the following index array[1]
.
Note: In C# arrays are collection of items, we can access it by using the element index. where the first element index is 0, the second element index is 1, etc.
Here is an example:
using System;
using System.Linq;
using System.Collections.Generic;
class GetSecondLowestNumber {
static void Main() {
int[] myArray = new int[] { 4, 24, 1, 20, 3, 40, 2 };
Array.Sort(myArray);
int secondLowest = myArray[1];
Console.WriteLine(secondLowest);
}
}
Output:
2
In the example above, we first sorted the array using the Array.Sort()
method by passing the array.
The Array.sort() returns the array in ascending order, so, we can get the second Lowest number by using the myArray[1]
.
Similarly, we can also get the second Lowest number in C# by using the following Linq
syntax.
using System;
using System.Linq;
using System.Collections.Generic;
class GetSecondLowestNumber {
static void Main() {
int[] myArray = new int[] { 4, 24, 1, 20, 3, 40, 2 };
int secondLowest = (from number in myArray
orderby number ascending
select number).Skip(1).First();
Console.WriteLine(secondLowest);
}
}