簡體   English   中英

C#從文本文件(具有不同的數據類型)讀取以獲取數值總和

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

所以我有一個.txt文件,內容如下:

-9
5.23
b
99
Magic
1.333
aa

然后,我將如何遍歷它以獲取所有數值的總和,而保持非數值不變?

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

在循環中,您可以:

  • 使用int.TryParse

  • 使用正則表達式僅匹配整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM