Call Extension Method on IEnumerable - C#

Shervan360 1,641 Reputation points
2023-02-08T02:42:33.88+00:00

Hi,

Why author/developer doesn't use Count() and Sum() extension methods in this article?

Is there any reason?

var numbers = new List<int> { 1, 2, 3 };
if (SumAndCount(numbers) is (Sum: var sum, Count: > 0))
{
    Console.WriteLine($"Sum of [{string.Join(" ", numbers)}] is {sum}");  // output: Sum of [1 2 3] is 6
}
static (double Sum, int Count) SumAndCount(IEnumerable<int> numbers)
{
    int sum = 0;
    int count = 0;
    foreach (int number in numbers)
    {
        sum += number;
        count++;
    }
    return (sum, count);
}

We can use:

            return (numbers.Sum(), numbers.Count());

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,296 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 119.9K Reputation points
    2023-02-08T05:36:51.0966667+00:00

    I think that the author did not want to enumerate large collections twice. The purpose was to show the usage of patterns.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.