Maximum integer value find in list<int>
I have a List<int>
with several elemen开发者_如何学Cts. 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.
Use Enumerable.Max
int max = l.Max();
int max = (from l in list select l).Max().FirstOrDefault();
as per comment this should be
l.Max();
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
精彩评论