CSharp examples for System.Collections.Generic:IEnumerable
Searches IEnumerable for the max or default element.
using System.Linq; using System.Collections.Generic; using System;// w ww. j a v a 2 s. com public class Main{ /// <summary> /// Searches for the max or default element. /// </summary> /// <typeparam name="T"> /// The type. /// </typeparam> /// <typeparam name="TR"> /// The comparing type. /// </typeparam> /// <param name="container"> /// The container. /// </param> /// <param name="valuingFoo"> /// The comparing function. /// </param> /// <returns></returns> public static T MaxOrDefault<T, TR>(this IEnumerable<T> container, Func<T, TR> valuingFoo) where TR : IComparable { var enumerator = container.GetEnumerator(); if (!enumerator.MoveNext()) { return default(T); } var maxElem = enumerator.Current; var maxVal = valuingFoo(maxElem); while (enumerator.MoveNext()) { var currVal = valuingFoo(enumerator.Current); if (currVal.CompareTo(maxVal) > 0) { maxVal = currVal; maxElem = enumerator.Current; } } return maxElem; } }