50

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 };

7 Answers 7

80

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.

0
13

Use Enumerable.Max

int max = l.Max();
7
int max = (from l in list select l).Max().FirstOrDefault();

as per comment this should be

l.Max();
2
  • 2
    Unless 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
  • @Yuriy your right - I am currently doing lots of Linq to EF and was forgetting that this was a simple l.Max(); I also made the assumption that List<int> which is declared in the title of this post is IEnumerable.
    – Rob
    Mar 14, 2011 at 5:45
4

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... .

3
using System.Linq;
using System.Collections.Generic;

int Max = list.Max();
4
  • 2
    This does answer the question! But I think Yuriy already has that covered.
    – jpaugh
    Feb 6, 2018 at 23:47
  • @jpaugh It answers the question, but it duplicates two of previous answers. Feb 7, 2018 at 2:00
  • I have used int Max = list.Max(); but in my case namespace using System.Linq; was missed therefore Max() not applied with list. Feb 7, 2018 at 5:45
  • while using IDE, it's obvious that using System.Linq is missing, but for online editors like on hackerrank etc, it's a important hint May 14, 2020 at 22:43
1
int max = listOfInts[0];
for(int i = 1; i < listOfInts.Count; i++) {
    max = Math.Max(max, listOfInts[i]);
}
0
1

If you don't want to use Linq:

l.Sort();
int min = l[0]; //1
int max = l[l.Count - 1]; //3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.