Click here to Skip to main content
15,891,184 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
25 Mar 2010CPOL 8.1K   1   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)


Written By
Software Developer (Senior) BitPlex Pty Ltd
Australia Australia
A professional developer in the Mining sector since 2000, Phil has a passion for creating robust, quality scientific applications.

I have started a software company, BitPlex, and I am focused on created a new and unique small business project planning tool called GamePlan.

My major fields of interest in software are 3D applications, visualisation, scheduling and optimisation, and novel UI design. My goal as a professional developer is to help people solve real world problems through reliable and fun to use software.

Comments and Discussions

 
QuestionI've found it useful Pin
Phil Martin6-Nov-11 5:01
professionalPhil Martin6-Nov-11 5:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.