简体   繁体   English

如何让LINQ返回集合中具有最大值的对象的索引?

[英]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? 有没有人有什么好建议?

It looks like there is a FindIndex method defined on List that would be perfect for this: 看起来在List上定义了一个FindIndex方法,对于这个方法是完美的:

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

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.

相关问题 Linq:如何在与值无关且具有动态列的分组查询中获得结果? - Linq: How can I get a result in a grouping query which is value agnostic and has dynamic columns? 如何获取在linq中具有最大日期的数据 - How to get data which has Max Date in linq 我如何在 Linq 中获得最大日期 - How can i get Max Date in Linq 使用 LINQ,其中一个 object 属性的值为 x,我如何在不同的属性中返回该值 - Using LINQ, where one object property has a value of x, how do I return the value in a different property LINQ 查询以获取有关 object 的所有数据,这是当集合的每个项目都有自己的集合时的对象集合 - LINQ query to get all data about object which is collection of objects when each item of collection has own collection 如何使用Linq获取与Max(值)相邻的值? - How do I get a value adjacent to a Max(value) using Linq? 如何使用LINQ返回类内集合的内容? - How can I return the contents of a collection inside a class using LINQ? 如何使用Linq返回列值已更改的行的列表或可枚举的行 - How can I return a list or enumerable of rows where column value has changed with Linq Linq:我如何获得 object 的值 - Linq: how i get the value of an object Entity Framework Core + Linq:如何获得具有最大值的整个实体? 寻找更优雅的解决方案 - Entity Framwork Core + Linq: How do I get the entire entity that has the max value? Looking for a more elegant solution
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM