Returns the maximum value in the stream based on the result of a project function. - CSharp System.IO

CSharp examples for System.IO:Stream

Description

Returns the maximum value in the stream based on the result of a project function.

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  a  v  a2s .co  m*/

public class Main{
        /// <summary>
        /// Returns the maximum value in the stream based on the result of a
        /// project function.
        /// </summary>
        /// <typeparam name="T">The stream type.</typeparam>
        /// <param name="that">The stream.</param>
        /// <param name="projectionFunction">The function that transforms the
        /// item.</param>
        /// <returns>The maximum value or null.</returns>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Used by at least one consumer of this class.")]
        public static T MaxOrNull<T>(this IEnumerable<T> that, Func<T, IComparable> projectionFunction)
            where T : struct
        {
            IComparable result = null;
            T maximum = default(T);
            if (!that.Any())
            {
                return maximum;
            }

            maximum = that.First();
            result = projectionFunction(maximum);
            foreach (T item in that.Skip(1))
            {
                IComparable currentResult = projectionFunction(item);
                if (result.CompareTo(currentResult) < 0)
                {
                    result = currentResult;
                    maximum = item;
                }
            }

            return maximum;
        }
}

Related Tutorials