CSharp examples for System.Collections.Generic:IEnumerable
Searches IEnumerable for the min or default element.
using System.Linq; using System.Collections.Generic; using System;/* w ww . java 2s.c o m*/ public class Main{ /// <summary> /// Searches for the min 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 MinOrDefault<T, TR>(this IEnumerable<T> container, Func<T, TR> valuingFoo) where TR : IComparable { var enumerator = container.GetEnumerator(); if (!enumerator.MoveNext()) { return default(T); } var minElem = enumerator.Current; var minVal = valuingFoo(minElem); while (enumerator.MoveNext()) { var currVal = valuingFoo(enumerator.Current); if (currVal.CompareTo(minVal) < 0) { minVal = currVal; minElem = enumerator.Current; } } return minElem; } }