Min

In this chapter you will learn:

  1. How to use Min operator
  2. Min with string value
  3. Min with object property
  4. Get to shortest word

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:

  1. How to use OfType operator
  2. How does OfType ignore the incompatible element
  3. Use Linq OfType to get value of specific type
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip