0

Using .NET Framework 4.7.2, I have a function that returns a Tuple and the returned values are then passed to another function in a foreach loop:

foreach ((var price, var discount) in Calculator.Compute(period, calculationComponent))
 {
  var rows = CreateCalculationRows(price, discount, otherParameters);
 }

The Compute function is declared as follow:

public static IEnumerable<(Price price, DiscountInfo discount)> Compute(Price price, CalcComponent calcComponent) { 
  ...
}

The code works fine, but I want to remove the foreach loop, since the Calculator.Compute() function, under some specific conditions that are always true in this specific case, returns a single row. I cannot simplify the Compute() return object, because it is used in many other functions.

How do I change the code to remove the foreach, so that the CreateCalculationRows() receives the parameters correctly ?

2
  • 2
    (Note, you can write var (price, discount) ..., which is slightly shorter) Commented Jan 13, 2020 at 16:44
  • You could use First or FirstOrDefault or something, but I think it would be a better idea to create a new method for Compute that only returns a single tuple instead of an IEnumerable to keep your code self-describing. Commented Jan 13, 2020 at 16:59

1 Answer 1

5

I'd expect something like this to work - just taking a single result and deconstructing that:

(var price, var discount) = Calculator.Compute(period, calculationComponent).Single();
var rows = CreateCalculationRows(price, discount, otherParameters);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.