Linq get max value from list

Linq get max value from list

In this tutorial I will show you how to get item in a list which has max value in the list. For demo purpose I have created a list of User Profiles with name and Age. Max Age is 45 and name of that item is Sat45.

Quick View

var maxAgeUser = userList.Where(u=>u.Age == userList.Max(x=>x.Age) )
                    .Select(u=> new { UserName = u.UserName, Age = u.Age} )
                    .FirstOrDefault();
     
                     Console.WriteLine(maxAgeUser.UserName);
    

Linq get max value from list of users example

void Main()
{
    
    var userList = new List<UserProfile>();
    
    
    var u1 = new UserProfile { UserName="Sat", Age = 31 };
    var u2 = new UserProfile { UserName="Sat45", Age = 45 };
    var u3 = new UserProfile { UserName="Sat2", Age = 40 };
    var u4 = new UserProfile { UserName="Sat3", Age = 35 };
    
    userList.Add(u1);
    userList.Add(u2);
    userList.Add(u3);
    userList.Add(u4);
    
    var maxAgeUser = userList.Where(u=>u.Age == userList.Max(x=>x.Age) )
                    .Select(u=> new { UserName = u.UserName, Age = u.Age} )
                    .FirstOrDefault();
     
                     Console.WriteLine(maxAgeUser.UserName);
    
    
}

public class UserProfile
{
  public string UserName
    {
     get;set;
    }
    
    public int Age
    {
    get;set;
    }
}

Extensions used are Where, Max, Select and FirstOrDefault.

Linq Inner JoinC# ArrayList Search using Linq Extension OfType Methodlistbox to listboxc# arraylistLinq Distinct ListHow to get Jquery selected optionJquery Dropdown Selected ValueLinq Group By Multiple ColumnsGet Selected Value From Dropdownlist [JQuery]Linq Split String To ListLinq Get Duplicate Count Of Words From String

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.