简体   繁体   English

C#从文本文件(具有不同的数据类型)读取以获取数值总和

[英]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: 所以我有一个.txt文件,内容如下:

-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? 然后,我将如何遍历它以获取所有数值的总和,而保持非数值不变?

使用System.IO.StreamReader读取文本文件,并使用Double.TryParse方法解析数字数据。

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

In your loop you can either: 在循环中,您可以:

  • Use int.TryParse 使用int.TryParse

  • Use Regular Expresssion to match only integers. 使用正则表达式仅匹配整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM