Returns the maximum value or null if sequence is empty. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Returns the maximum value or null if sequence is empty.

Demo Code


using System.Reflection;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;/*from w w w. j av  a  2s  .  c o  m*/

public class Main{
        /// <summary>
        /// Returns the maximum value or null if sequence is empty.
        /// </summary>
        /// <typeparam name="T">The type of the sequence.</typeparam>
        /// <param name="that">The sequence to retrieve the maximum value from.
        /// </param>
        /// <returns>The maximum value or null.</returns>
        public static T? MaxOrNullable<T>(this IEnumerable<T> that)
            where T : struct, IComparable
        {
            if (!that.Any())
            {
                return null;
            }
            return that.Max();
        }
}

Related Tutorials