如何使用LINQ查找具有最低值的元素?

我有一系列元素。我想从这些元素中找到最低的值,但它们没有属性,我必须先计算该值并进行比较。


我的伪代码:


        int currentLowestValue = int.MaxValue;

        MyObj targetElement = null;


        for (int i = 0; i < elements.Length; i++)

        {

            MyObj ele = elements[i];

            int val = ele.CalculateValue() + GetOtherValue();


            if (val < currentLowestValue)

            {

                targetElement = ele;

                currentLowestValue = val;

            }

        }

如何选择ele.CalculateValue() + GetOtherValue();使用Linq计算出的最小值的元素?


呼唤远方
浏览 225回答 2
2回答

墨色风雨

基于如何使用LINQ选择具有最小或最大属性值的对象MyObj targetElement = elements.Aggregate((curMin, x) => (curMin == null || x.CalculateValue() < curMin.CalculateValue() ? x : curMin));int currentLowestValue = targetElement.CalculateValue() + GetOtherValue();由于值GetOtherValue() 似乎是静态的(不变),因此在计算中不需要它来查找具有最小值的元素。如果此方法不是幂等的,则需要将其添加到循环中,并将结果缓存在聚合中。
打开App,查看更多内容
随时随地看视频慕课网APP