• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 88
  • Last Modified:

LINQ: Sum of a numeric collection

Do the below perform the same result with the same performance? The end-goal is sum up all the amounts in the downPaymentsList.

totalDownPayments = downPaymentsList.AsEnumerable().Sum(dp => (decimal)dp.Amount.Value);

downPaymentsList.AsEnumerable().ToList().ForEach(dp => totalDownPayments += dp.Amount.Value);
1 Solution
Fernando SotoRetiredCommented:
Hi pzozulka;

Both use Extension methods but the Sum function will return 0, zero, if the list is empty where the ForEach method does not return anything and depends on the lambda expression to set your value. Also the Sum method is self documenting where as the ForEach you need to read the code to see what it is doing.

IMHO I would use the Sum method.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now