[英]Converting string array to double array
I have a file with alot of numbers, each index has 4 subnumbers 我有一个带有很多数字的文件,每个索引都有4个子数字
no1 no2 no3 no4
no1 no2 no3 no4
no1 no2 no3 no4
The file is a cvs file, but I need to read the numbers into an array as type double and make an interpolating, so I need to walkthrough the table. 该文件是cvs文件,但是我需要将数字读入数组中,类型为double类型并进行插值,因此我需要遍历表。
Until now I have this, but I am stuck and do not really know how I nicely can convert the file to double values, so I can start calculate on them. 到现在为止,我仍然遇到这个问题,但是我还停留在上面,还不太了解如何将文件转换为双精度值,因此我可以对其进行计算。 Any suggestion ?
有什么建议吗?
var filelines = from line in file.Skip(5)
select line.Split(';');
您可以分割线,将每个部分解析为十进制,然后使用SelectMany展平结果:
file.Skip(5).SelectMany(line => line.Split(';').Select(decimal.Parse)).ToArray()
If you want a double[][]
, so one array per line: 如果要
double[][]
,那么每行一个数组:
double d;
double[][] lineValues = file.Skip(5)
.Select(l => l.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries))
.Where(arr => arr.Length == 4 && arr.All(s => double.TryParse(s, out d)))
.Select(arr => arr.Select(double.Parse).ToArray())
.ToArray();
If there is certain values in each row, like let's say your cvs data store has a specific number of fields, s wiser and strongly typed move is to first make up a model for your data store, which according to the information you provided would be: 如果每行中都有某些值,例如您的cvs数据存储区具有特定数量的字段,那么明智且强类型的举动是首先为数据存储区建立一个模型,根据您提供的信息, :
public class MyCVSModel {
public Double Number1 {get; set;}
public Double Number2 {get; set;}
public Double Number3 {get; set;}
public Double Number4 {get; set;}
}
Now, you can: 现在你可以:
public static IEnumerable<MyCVSModel> Converion(String FileName){
var AllLines = System.IO.ReadAllLines(FileName);
foreach(var i in AllLines){
var Temp = i.Split('\t'); // Or any other delimiter
if (Temp.Lenght >= 4){ // 4 is because you have 4 values in a row
List<Double> TryConversion = new List<Double>();
foreach(var x in Temp) {
if (IsDouble(x))
TryConversion.Add(Convert.ToDouble(x));
else
TryConversion.Add(0);
}
MyCVSModel Model = new MyCVSModel();
Model.Number1 = TryConversion[0];
Model.Number2 = TryConversion[1];
Model.Number3 = TryConversion[2];
Model.Number4 = TryConversion[3];
yield return Model;
}
}
}
public static Boolean IsDouble(String Value) {
Regex R = new Regex(@"^[0-9]*(?:\.[0-9]*)?$");
return R.IsMatch(Value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.