开发者

C# reading from text file (which has different data types) to get sum of numerical values

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 th开发者_如何学Goe non-numerical values untouched?


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);
    }
}


Read text file using System.IO.StreamReader and use Double.TryParse method to parse the numeric data.


In your loop you can either:

  • Use int.TryParse

  • Use Regular Expresssion to match only integers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜