Can I add a list of integers directly without looping through it?
I have a List of integers -
List<int> intlist= new List<int>();
Can I just say 开发者_如何学JAVA-
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 that list without looping through it.
Yes, you can use Sum
like that. 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
.
It's actually an extension method Enumerable.Sum
added in .NET 3.5 and it works on more than just lists.
Of course internally this still loops through the numbers and adds them, but it's a lot easier to call this method than to write it yourself. Using .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;
}
Note that there is also a Queryable.Sum
method. This allows you to sum numbers in a database without fetching them and looping through them locally. Instead the sum operation can be performed in the database and only the result returned.
To calculate the sum of a list, you either need to calculate it as items are added or go through the list later. If you call a function that goes through the list, or go through the list yourself, there isn't much difference.
So, to answer your question, No, unless you calculate the sum as items are added.
What language is this, for what it is worth?
This link may help you.
""You want to compute the sum total of all the numbers in an array of integers or List of integers in the C# programming language. The Sum extension method in LINQ provides an excellent way to do this with minimal calling code, but 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 the C# language, seeing an example on an array and List""
精彩评论