Can I add a list of integers directly, without focusing on it?

I have a list of integers -

List<int> intlist= new List<int>();

Can I just say -

intlist.Sum();//I know sum() is already there as a function but I dont know how I can use it

and get the sum of this list without scrolling it.

+3
source share
3 answers

Yes, you can use Sumlike this. Just assign the result to something:

int s = intList.Sum();

Now you have the sum of the numbers in the list stored in a variable called s.

This is actually an extension method added in .NET 3.5, and it works not only with lists. Enumerable.Sum

Of course, internally this still goes through the numbers and adds them, but it is much easier to name this method than to write it yourself. Using the .NET Reflector you can see that the implementation is quite simple:

public static int Sum(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }

    int num = 0;
    foreach (int num2 in source)
    {
        num += num2;
    }
    return num;
}

, Queryable.Sum. , . , .

+10

, , , . , , , .

, , , .

, ?

+2

.

“You want to calculate the sum of all the numbers in an array of integers or a List of integers in the C # programming language. The LINQ extension Sum method provides a great way to do this with a minimal calling code, but it has some drawbacks as well as pluses. Here we look at how you can use the Sum extension method from the System.Linq namespace in C #, seeing an example of an array and List ""

0
source

Source: https://habr.com/ru/post/1748932/


All Articles