Max
How do you find the largest number in an array? In Linq we can use the Max
method.
Basic example
Here we have a list of numbers. We can use the Max
method, it will return the largest number.
Live example: https://dotnetfiddle.net/s7tPiK
var scores = new[] {2, 4, 6, 8, 10};
var max = scores.Max();
// output: 10
Max with objects
Just like the Max
method operator, finding the largest number in a list can also be applied to a list of objects.
The only difference is that we need to specify a property on the object. In the example below, we want to use the Age
property.
Live example: https://dotnetfiddle.net/KQenz3
var people = new[]
{
new
{
Name = "Vernon", Age = 21
},
new
{
Name = "Carrie", Age = 24
},
new
{
Name = "Joanna", Age = 20
}
};
var max = people.Max(arg => arg.Age);