Min
In this chapter you will learn:
Get to know Min operator
Min
returns the smallest element from a sequence:
using System;/*from j a va 2s .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.Min(); // 14;
Console.WriteLine(smallest);
}
}
The output:
Min with string value
using System;/*from j a va2s . c om*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "java2s.com", "a", "H", "over", "Jack"};
string minName = presidents.Min();
Console.WriteLine(minName);
}
}
Min with object property
using System;//from java 2 s . c o m
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 = "Keanu", lastName = "Reeves" },
new Employee { birthYear = 1968, firstName = "Owen", lastName = "Wilson" },
new Employee { birthYear = 1960, firstName = "James", lastName = "Spader" },
new Employee { birthYear = 1964, firstName = "Sandra", lastName = "Bullock" },
};
return (actors);
}
}
public class MainClass {
public static void Main() {
int oldestEmployeeAge = Employee.GetEmployees().Min(a => a.birthYear);
Console.WriteLine(oldestEmployeeAge);
}
}
Get to shortest word
The following code
uses Min
to get the length of the shortest word in a string array.
using System;/*from j a v a 2 s . com*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
string[] words = { "cherry", "apple", "blueberry" };
int shortestWord = words.Min(w => w.Length);
Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
}
}
Next chapter...
What you will learn in the next chapter:
- How to use OfType operator
- How does OfType ignore the incompatible element
- Use Linq OfType to get value of specific type
Home » C# Tutorial » Linq Operators