Better in what way? Faster? Less written code?
–
Fredrik MörkMar 10 '10 at 18:13

3

People are so weird these days. "If there is not already a function for something, it is wrong". How much more simple can you get; iterate over the array, add them together. Yeesh.
–
Ed S.Mar 10 '10 at 18:30

1

Also, LOL at "cleaner code". What do you think the library's Array.Sum is doing when you call it?
–
Ed S.Mar 10 '10 at 18:30

4

@Ed: I'm not that daft to think that the less code i write, the faster it runs. But less code is more readable for sure and cleaner in that way.
–
FilburtMar 10 '10 at 22:00

The identity lambda isn't necessary. Except to confuse the new guy on the team.
–
WillMar 10 '10 at 18:23

1

It is worth noting that this will get raise an error System.OverflowException if the result would be greater than you can fit in a signed 32 bit integer (i.e. (2^31) -1 or in english ~ 2.1 billion).
–
ChrisProsserMar 14 at 20:15

Why such a convoluted pre 3.5 version? The foreach loop is available in all versions of C#.
–
Jørn Schou-RodeMar 16 '10 at 9:37

@Jørn: the OP asked for a shorter approach. A foreach just substitutes one line of code for another and isn't shorter. Apart from that a foreach is perfectly fine and is more readable.
–
Ahmad MageedMar 16 '10 at 11:34

It depends on how you define better. If you want the code to look cleaner, you can use .Sum() as mentioned in other answers. If you want the operation to run quickly and you have a large array, you can make it parallel by breaking it into sub sums and then sum the results.

its the basic coding for the C# beginners who were able to easily understand it.
–
sudharsanDec 19 '14 at 5:28

I don't quite understand how repeating the approach of my question is a useful answer. Back when I posted this question I simply wasn't aware of the according Linq Extension Method .Sum().
–
FilburtDec 19 '14 at 8:05

Thanks for your suggestion Mr.Ben Voigt. here i added the coding for using "ForEach". Without foreach my above program will use. Keep commenting me and encourage me for getting more interest in C# language.
–
sudharsanDec 24 '14 at 9:53