C# Enumerable Min(IEnumerable)

Description

Returns the minimum value in a generic sequence.

Syntax


public static TSource Min<TSource>(
  this IEnumerable<TSource> source
)

Parameters

  • TSource - The type of the elements of source.
  • source - A sequence of values to determine the minimum value of.

Returns

Returns the minimum value in a generic sequence.

Example

The following code example demonstrates how to use Min to determine the minimum value in a sequence of IComparable objects.


//from  w  w w .jav  a  2 s. c  o m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    Pet[] pets = { new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };

    Pet min = pets.Min();

    Console.WriteLine(min.Name);
  }
}

class Pet : IComparable<Pet>
{
    public string Name { get; set; }
    public int Age { get; set; }
    int IComparable<Pet>.CompareTo(Pet other)
    {
        if (other.Age > this.Age)
            return -1;
        else if (other.Age == this.Age)
            return 0;
        else 
            return 1;
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable