[英]How can I get LINQ to return the index of the object which has the max value in a collection?
I have a list of immutable objects (in my specific case a list of Tuple<double, double>
) and I'd like to change the one with the highest Item2 value. 我有一个不可变对象列表(在我的特定情况下是一个
Tuple<double, double>
列表Tuple<double, double>
),我想更改具有最高Item2值的那个。
Ideally there would be an IndexOfMaxBy function I could use, so I could do: 理想情况下会有一个我可以使用的IndexOfMaxBy函数,所以我可以这样做:
var indexOfPointWithHighestItem2 = myList.IndexOfMaxBy(x => x.Item2);
var original = myList[indexOfPointWithHighestItem2];
myList[indexOfPointWithHighestItem2] =
new Tuple<double, double>(original.Item1, original.Item2 - 1);
I have seen How can I get LINQ to return the object which has the max value for a given property? 我已经看到如何让LINQ返回具有给定属性的最大值的对象? , and using Jon Skeet 's MaxBy function combined with Select I could do:
,并使用Jon Skeet的MaxBy功能与Select我可以做到:
var indexOfPointWithHighestItem2 =
myList.Select((x, i) => new { Index = i, Value = x })
.MaxBy(x => x.Item2).Index;
But this creates a new object for every object in my list, and there must be a neater way. 但是这会为我列表中的每个对象创建一个新对象,并且必须有一个更简洁的方法。 Does anyone have any good suggestions?
有没有人有什么好建议?
Well, if you wanted to, you could of course write an IndexOfMaxBy
extension yourself. 好吧,如果你想,你当然可以自己写一个
IndexOfMaxBy
扩展。
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;
}
}
Usage: 用法:
var indexOfPointWithHighestItem2 = myList.IndexOfMaxBy(x => x.Item2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.