0

I have the following method containing a simple foreach loop in a C# class. The method returns the sum of totals calculated using a function on a separate class.

    private readonly ICalculateTotalService _calculateTotalService;

    public decimal GetTotal(IOrder order)
    {
        decimal paidTotal = 0;

        foreach (var line in order.Lines)
        {
            paidTotal += _calculateTotalService.GetTotal(line);
        }

        return paidTotal;
    }

Resharper is suggesting that this can be refactored into a LINQ statement. What would the best way be to go about doing this?

3
  • 7
    You can let Resharper make the change. You should be able to click on an icon in the margin. Commented Jan 11, 2016 at 15:15
  • 2
    Let ReSharper do the change and then if you don't understand what it's done, post the original and modified code and ask why they're equivalent. Commented Jan 11, 2016 at 16:25
  • 1
    As others have said, just click the lightbulb and let it do the change for you. I will mention that it may not always be best to convert it - I've had some really clean and readable code and had ReSharper suggest converting it, so I did the suggestion and it became a jumbled and unreadable mess. You have to make the call on what is more readable. In your case I think the LINQ query will come out just as readable (if not more) than what you have now. Commented Jan 11, 2016 at 18:28

1 Answer 1

5

If IOrder.Lines is IEnumerable type or similar that supports LINQ:

private readonly ICalculateTotalService _calculateTotalService;

public decimal GetTotal(IOrder order)
{
    return order.Lines.Sum(line => _calculateTotalService.GetTotal(line));
}
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.