Max() extension method but using a separate scorer and selector






3.67/5 (2 votes)
This does the same as Enumerable.Max(), but allows for a second function to select the result, rather than returning the usually useless score./// /// Transforms each item of the sequence to a double score using the function, and finds the maximum scored...
This does the same as Enumerable.Max(), but allows for a second function to select the result, rather than returning the usually useless score.
/// <summary>
/// Transforms each item of the sequence to a double score using the <paramref name="scorer"/> function, and finds the maximum scored item. The result is the maximum scored item but transformed using the <paramref name="selector"/> function.
/// </summary>
/// <typeparam name="T">The input sequence element type</typeparam>
/// <typeparam name="U">The reslt element type</typeparam>
/// <param name="items">The input sequence</param>
/// <param name="scorer">The function to score each element</param>
/// <param name="selector">The function to transform an input element into a result element</param>
/// <returns>The transformed item with the largest score</returns>
public static U Max<T, U>(this IEnumerable<T> items, Func<T, double> scorer, Func<T, U> selector)
{
var firstTime = true;
var bestScore = 0.0;
var bestItem = default(T);
foreach (var i in items)
{
var score = scorer(i);
if (firstTime || score > bestScore)
{
firstTime = false;
bestItem = i;
bestScore = score;
}
}
return selector(bestItem);
}