Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This would require a sort (O(n <em>log</em> n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL:</p> <pre><code>var maxObject = list.OrderByDescending(item =&gt; item.Height).First(); </code></pre> <p>Note that this has the advantage of enumerating the <code>list</code> sequence just once. While it might not matter if <code>list</code> is a <code>List&lt;T&gt;</code> that doesn't change in the meantime, it could matter for arbitrary <code>IEnumerable&lt;T&gt;</code> objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own <code>MaxObject</code> extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)):</p> <pre><code>static class EnumerableExtensions { public static T MaxObject&lt;T,U&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T,U&gt; selector) where U : IComparable&lt;U&gt; { if (source == null) throw new ArgumentNullException("source"); bool first = true; T maxObj = default(T); U maxKey = default(U); foreach (var item in source) { if (first) { maxObj = item; maxKey = selector(maxObj); first = false; } else { U currentKey = selector(item); if (currentKey.CompareTo(maxKey) &gt; 0) { maxKey = currentKey; maxObj = item; } } } if (first) throw new InvalidOperationException("Sequence is empty."); return maxObj; } } </code></pre> <p>and use it with:</p> <pre><code>var maxObject = list.MaxObject(item =&gt; item.Height); </code></pre>
    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