0

I have an array of elements. I want to find the lowest value from these elements but they have no property, I have to calculate the value and compare it first.

My pseudo code:

        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;
            }
        }

How can I select the element with the lowest value calculated out of ele.CalculateValue() + GetOtherValue(); by using Linq?

dymanoid
  • 14,771
  • 4
  • 36
  • 64
Question3r
  • 2,166
  • 19
  • 100
  • 200

2 Answers2

3

You can use an anonymous type to store the result of the calculation and the object.

int otherVal = GetOtherValue(); // why you calculated it in the loop?
var lowestValObj = elements
    .Select(x => new { MyObj = x, Value = x.CalculateValue() + otherVal})
    .OrderBy(x => x.Value)
    .First();
MyObj targetElement = lowestValObj.MyObj;
int lowestVal = lowestValObj.Value;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • One reason to call GetOtherValue inside the loop would be if it did not return the same value every call. – PaulF May 02 '18 at 15:42
  • @PaulF: maybe, then it's easy to replace `otherVal` with `GetOtherValue()` – Tim Schmelter May 02 '18 at 15:49
  • Just answering your comment - but as you suggest, if the value is unchanging then it would be better to calculate it the once. – PaulF May 02 '18 at 15:53
1

Based on How to use LINQ to select object with minimum or maximum property value

MyObj targetElement = elements.Aggregate((curMin, x) => (curMin == null || x.CalculateValue() < curMin.CalculateValue() ? x : curMin));
int currentLowestValue = targetElement.CalculateValue() + GetOtherValue();

As the value of GetOtherValue() seems to be static (unchanging) you do not need it in the calculation to find the element with the smallest value. If this method is not idempotent then you would need to add it to the loop and cache the results in the aggregate.

Igor
  • 60,821
  • 10
  • 100
  • 175