Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unfortunately there isn't a built-in method to do this.</p> <blockquote> <p>PM> Install-Package morelinq</p> </blockquote> <pre><code>var firstBorn = People.MinBy(p =&gt; p.DateOfBirth ?? DateTime.MaxValue); </code></pre> <p>Alternatively, you can use the implementation we've got in <a href="https://github.com/morelinq/MoreLINQ" rel="noreferrer">MoreLINQ</a>, in <a href="https://github.com/morelinq/MoreLINQ/blob/ec4bbd3c7ca61e3a98695aaa2afb23da001ee420/MoreLinq/MinBy.cs" rel="noreferrer">MinBy.cs</a>. (There's a corresponding <code>MaxBy</code>, of course.) Here are the guts of it:</p> <pre><code>public static TSource MinBy&lt;TSource, TKey&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; selector) { return source.MinBy(selector, null); } public static TSource MinBy&lt;TSource, TKey&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; selector, IComparer&lt;TKey&gt; comparer) { if (source == null) throw new ArgumentNullException("source"); if (selector == null) throw new ArgumentNullException("selector"); comparer = comparer ?? Comparer&lt;TKey&gt;.Default; using (var sourceIterator = source.GetEnumerator()) { if (!sourceIterator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } var min = sourceIterator.Current; var minKey = selector(min); while (sourceIterator.MoveNext()) { var candidate = sourceIterator.Current; var candidateProjected = selector(candidate); if (comparer.Compare(candidateProjected, minKey) &lt; 0) { min = candidate; minKey = candidateProjected; } } return min; } } </code></pre> <p>Note that this will throw an exception if the sequence is empty, and will return the <em>first</em> element with the minimal value if there's more than one.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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