LINQ Queries are similar to SQL, So we can use “order by” with desc parametre.
After sorting highest to lowest with “order by descending”, select the first item. Because first item is going to be the highest value. And you can even use “order by ascending” to sort as ascending.
Here is the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Program { static void Main(string[] args) { //given list List<int> numbers = new List<int> { 21, 83, 13, 26, 45, 102 }; //Linq Query Syntax, getting max value int maxNumber = (from x in numbers orderby x descending select x).First(); //Linq Query Syntax, getting min value int minNumber = (from x in numbers orderby x ascending select x).First(); Console.WriteLine("Min Number: " + minNumber.ToString()); Console.WriteLine("Max Number: " + maxNumber.ToString()); Console.ReadLine(); } } |
Output: