I have a List<int> with several elements. I know I can get all the values if I iterate through it with foreach, but I just want the maximum int value in the list.
var l = new List<int>() { 1, 3, 2 };
Assuming .NET Framework 3.5 or greater:
var l = new List<int>() { 1, 3, 2 };
var max = l.Max();
Console.WriteLine(max); // prints 3
Lots and lots of cool time-savers like these in the Enumerable class.
int max = (from l in list select l).Max().FirstOrDefault();
as per comment this should be
l.Max();
l is a list of Enumerables this won't compile, also there is no point in (from l in list select l)
Mar 14, 2011 at 5:36
You Can Use this Syntax:
l.OrderByDescending(x => x).First(); //for maximum
l.OrderBy(x => x).First(); // for minimum
or You can use Max() and Min() Methods from linq.
I hope what I said will be useful to you... .
using System.Linq;
using System.Collections.Generic;
int Max = list.Max();
int max = listOfInts[0];
for(int i = 1; i < listOfInts.Count; i++) {
max = Math.Max(max, listOfInts[i]);
}
If you don't want to use Linq:
l.Sort();
int min = l[0]; //1
int max = l[l.Count - 1]; //3