How can I get LINQ to return the index of the object with the maximum value in the collection?

I have a list of immutable objects (in my particular case, a Tuple<double, double> list), and I would like to change the one that has the highest Item2 value.

Ideally, there would be an IndexOfMaxBy function that I could use, so I could do:

 var indexOfPointWithHighestItem2 = myList.IndexOfMaxBy(x => x.Item2); var original = myList[indexOfPointWithHighestItem2]; myList[indexOfPointWithHighestItem2] = new Tuple<double, double>(original.Item1, original.Item2 - 1); 

I saw. How do I get LINQ to return the object with the maximum value for this property? and using Jon Skeet MaxBy Function combined with Select, which I could do:

 var indexOfPointWithHighestItem2 = myList.Select((x, i) => new { Index = i, Value = x }) .MaxBy(x => x.Item2).Index; 

But this creates a new object for each object in my list, and it should be more accurate. Does anyone have any good suggestions?

+4
source share
2 answers

Well, if you wanted to, you could, of course, write the IndexOfMaxBy extension yourself.

Example (untested):

 public static int IndexOfMaxBy<TSource, TProjected> (this IEnumerable<TSource> source, Func<TSource, TProjected> selector, IComparer<TProjected> comparer = null ) { //null-checks here using (var erator = source.GetEnumerator()) { if (!erator.MoveNext()) throw new InvalidOperationException("Sequence is empty."); if (comparer == null) comparer = Comparer<TProjected>.Default; int index = 0, maxIndex = 0; var maxProjection = selector(erator.Current); while (erator.MoveNext()) { index++; var projectedItem = selector(erator.Current); if (comparer.Compare(projectedItem, maxProjection) > 0) { maxIndex = index; maxProjection = projectedItem; } } return maxIndex; } } 

Using:

 var indexOfPointWithHighestItem2 = myList.IndexOfMaxBy(x => x.Item2); 
+4
source

There seems to be a FindIndex method defined on a List that would be ideal for this:

 double max = myList.Max(t => t.Item2); int index = myList.FindIndex(t => t.Item2 == max); 
+4
source

Source: https://habr.com/ru/post/1342226/


All Articles