Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There isn't a built-in way of doing this, unfortunately - but it's really easy to write an extension method to do it.</p> <p>It was in <a href="http://msmvps.com/blogs/jon_skeet/archive/2005/10/02/a-short-case-study-in-linq-efficiency.aspx" rel="nofollow noreferrer">one of my very first blog posts</a>, in fact... note that there's a better implementation in one of the comments. I'll move it into the body if I get time. </p> <p>EDIT: Okay, I have a slightly abbreviated version - it just returns the maximal element, using the given selector. No need to do a projection as well - do that once afterwards if you need to. Note that you could remove the constraint on <code>TValue</code> and use <code>Comparer&lt;TValue&gt;.Default</code> instead, or have an overload which allows the comparison to be specified as another parameter.</p> <pre><code>public static TSource MaxBy&lt;TSource, TValue&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TValue&gt; selector) where TValue : IComparable&lt;TValue&gt; { TValue maxValue = default(TValue); TSource maxElement = default(TSource); bool gotAny = false; foreach (TSource sourceValue in source) { TValue value = selector(sourceValue); if (!gotAny || value.CompareTo(maxValue) &gt; 0) { maxValue = value; maxElement = sourceValue; gotAny = true; } } if (!gotAny) { throw new InvalidOperationException("source is empty"); } return maxElement; } </code></pre> <p>Sample use: (note type inference):</p> <pre><code>string maxName = models.MaxBy(model =&gt; model.Name.Length).Name; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload