Max
In this chapter you will learn:
- How to use Max operator
- Max with filter delegate
- Max among string array
- Max for custom types
- How to get the longest word
Get to know Max operator
Max returns the smallest or largest element from a sequence:
using System;//from j a v a2 s . c o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 28, 32, 14 };
int largest = numbers.Max(); // 32;
Console.WriteLine(largest);
}
}
The output:
Max with filter delegate
If you include a selector expression:
using System;/*j av a 2 s. c o m*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 28, 32, 14 };
int smallest = numbers.Max(n => n % 10); // 8;
Console.WriteLine(smallest);
}
}
The output:
Max among string array
using System;/*from j a v a 2 s . c o m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "H", "H", "java2s.com", "H", "J"};
string maxName = presidents.Max();
Console.WriteLine(maxName);
}
}
Max for custom types
using System;//ja v a 2 s . c om
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Employee {
public int birthYear;
public string firstName;
public string lastName;
public static Employee[] GetEmployees() {
Employee[] actors = new Employee[] {
new Employee { birthYear = 1964, firstName = "K", lastName = "R" },
new Employee { birthYear = 1968, firstName = "O", lastName = "W" },
new Employee { birthYear = 1960, firstName = "J", lastName = "S" },
new Employee { birthYear = 1964, firstName = "S", lastName = "B" },
};
return (actors);
}
}
public class MainClass {
public static void Main() {
int youngestEmployeeAge = Employee.GetEmployees().Max(a => a.birthYear);
Console.WriteLine(youngestEmployeeAge);
}
}
Max word length
The following code uses Max to get the length of the longest word in a string array.
using System;/*ja va2 s . c o m*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
string[] words = { "cherry", "apple", "blueberry" };
int longestLength = words.Max(w => w.Length);
Console.WriteLine("The longest word is {0} characters long.", longestLength);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Linq Operators