Author -  Sai gowtham

How to get the Maximum Value from a list in C#

Learn, how to get the maximum value from a list in C# with the help of examples.

Consider, we have a following list in our code.

List<int> numsList = new List<int>() {10, 23, 400, -2, 0, 12, 3};

Now, we need to get the maximum value from a above list in C#.

Get the Maximum value from a list

To get the maximum value from a list in C#, we can use the built-in Linq Max() method. So, It returns the maximum value from the given list.

Here is an example:

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

class GetMaximumValue {
  static void Main() {
      List<int> numsList = new List<int>() {10, 23, 400, -2, 0, 12, 3};
      int maxValue = numsList.Max();
      Console.WriteLine(maxValue);
  }
}

Output:

400

In the example above, we have used the Max() method on a numsList. So, it returns the Maximum value 400 from it.

The Max() in C# returns the maximum value from the sequence of values.

The above method only works if the list is not empty. So, if a user passes an empty list we can return a value 0 instead of error InvalidOperationException in terminal with the help of Any() method.

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

class GetMaximumValue {
  static void Main() {
      List<int> numsList = new List<int>() {};
      int maxValue = numsList.Any() ? numsList.Min() : 0;
      Console.WriteLine(maxValue);
  }
}

Output:

0

Similarly, you can also get the lowest value from a list by using the Min() method in C#.

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

class GetLowestValue {
  static void Main() {
      List<int> numsList = new List<int>() {100, 23, 40, -2, 0, 12, 3};
      int lowestValue = numsList.Min();
      Console.WriteLine(lowestValue);
  }
}

Output:

-2

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY