Reputation: 13
So i'm currently building a .NC1 file reader for my employer and i'm trying to figure out a quick/efficient way to add the values stores in a string.
As per the ss above i have a string called line which the following attached to it:
270.00 0.00 0.00 0.00 0.00 0.00 0.00
All i'm asking for it to do is add the 270.00 + 0.00 + 0.00 etc...
Above are the lines in which I will then try to add. (Ignore the first line with v as its default values will always be 0.
Any suggestions?
Upvotes: 0
Views: 91
Reputation: 412
You can use .Split()
on the string, like this:
string[] values = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
Then just loop through the values
array and convert the values to float and add them:
float sum = 0;
foreach (string item in values)
{
sum += float.Parse(item);
}
Upvotes: 0
Reputation: 2166
Using LINQ:
var result = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(number => decimal.Parse(number))
.Sum();
Upvotes: 1