[英]Reading data from a text file into a struct with different data types 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.