Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I suggest writing your own extension method (edited to be generic with an <code>IComparable&lt;T&gt;</code> constraint.)</p> <pre><code>public static int MaxIndex&lt;T&gt;(this IEnumerable&lt;T&gt; sequence) where T : IComparable&lt;T&gt; { int maxIndex = -1; T maxValue = default(T); // Immediately overwritten anyway int index = 0; foreach (T value in sequence) { if (value.CompareTo(maxValue) &gt; 0 || maxIndex == -1) { maxIndex = index; maxValue = value; } index++; } return maxIndex; } </code></pre> <p>Note that this returns -1 if the sequence is empty.</p> <p>A word on the characteristics:</p> <ul> <li>This works with a sequence which can only be enumerated once - this can sometimes be very important, and is generally a desirable feature IMO.</li> <li>The memory complexity is O(1) (as opposed to O(n) for sorting)</li> <li>The runtime complexity is O(n) (as opposed to O(n log n) for sorting)</li> </ul> <p>As for whether this "is LINQ" or not: if it had been included as one of the standard LINQ query operators, would you count it as LINQ? Does it feel particularly alien or unlike other LINQ operators? If MS were to include it in .NET 4.0 as a new operator, would it be LINQ?</p> <p>EDIT: If you're really, really hell-bent on using LINQ (rather than just getting an elegant solution) then here's one which is still O(n) and only evaluates the sequence once:</p> <pre><code>int maxIndex = -1; int index=0; double maxValue = 0; int urgh = sequence.Select(value =&gt; { if (maxIndex == -1 || value &gt; maxValue) { maxIndex = index; maxValue = value; } index++; return maxIndex; }).Last(); </code></pre> <p>It's hideous, and I don't suggest you use it at all - but it will work.</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. 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