Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

3.67/5 (2 votes)
25 Mar 2010CPOL 1  
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.

C#
/// <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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)