Reputation: 1832
So I have a .txt file that reads as the following:
-9
5.23
b
99
Magic
1.333
aa
how would I then loop through it to get the sum of all numerical values, and leave the non-numerical values untouched?
Upvotes: 0
Views: 979
Reputation: 40145
using System;
using System.IO;
using System.Linq;
class Sample {
static void Main(){
string[] data = File.ReadAllLines("data.txt");
double sum = data.Select( x => {double v ;Double.TryParse(x, out v);return v;}).Sum();
Console.WriteLine("sum:{0}", sum);
}
}
Upvotes: 2
Reputation: 94635
Read text file using System.IO.StreamReader
and use Double.TryParse
method to parse the numeric data.
Upvotes: 2
Reputation: 1342
In your loop you can either:
Use int.TryParse
Use Regular Expresssion to match only integers.
Upvotes: 0