从c#中的文本文件计算平均值

时间:2015-02-19 17:42:43

标签: c# arrays multidimensional-array

我有一个文本文件:

D:2013:09:1:H:30:P:992:R:29:T:39:W:28:D:2013:09:2:P:1009:T:3 
3:D:2013:09:3:H:31:P:1001:T:33:W:15:D:2013:09:4:H:20:R:5:T:7 
1:W:31:D:2013:09:5:P:991:T:36:D:2013:09:6:H:74:P:1005:R:95:T 
:82:W:34:D:2013:09:7:P:1000:T:55:W:30:D:2013:09:8:H:55:P:982 
:T:49:W:22:D:2013:09:9:H:73:P:997:T:58:W:27:D:2013:09:10:H:5 
2:P:993:D:2013:09:11:H:27:P:1010:R:32:W:26:D:2013:09:12:H:71 
:P:1018:R:91:T:74:W:6:D:2013:09:13:H:89:P:996:R:95:T:75:W:26 
:D:2013:09:14:P:1013:R:10:W:13:D:2013:09:15:P:1014:T:66:W:21 
:D:2013:09:16:P:1010:R:25:T:21:W:30:D:2013:09:17:P:1007:D:20 
13:09:18:P:992:R:59:W:29:D:2013:09:19:T:80:W:10:D:2013:09:20 
:D:2013:09:21:P:985:T:64:W:18:D:2013:09:22:H:32:P:1007:W:10: 
D:2013:09:23:H:60:P:1009:T:48:W:15:D:2013:09:24:P:986:T:62:D 
:2013:09:25:T:48:D:2013:09:26:D:2013:09:27:H:57:P:986:R:99:T 
:56:W:23:D:2013:09:28:P:996:W:32:D:2013:09:29:P:1018:T:47:D: 
2013:09:30:H:77:T:73:W:7:************************************

一整套数据是D:2013:09:1:H:30:P:992:R:29:T:39:W:28

可以看出,所有数据项都以冒号(':')分隔。字母D,H,P,R,T,W分别代表日期,湿度,压力,降雨量,温度和风速

(编辑:如果没有阅读文件的话,那就是那天它意味着它已经为0了。)

分离数据后,如何将数据格式化为能够计算每个数据项平均值的二维数组?

目前我的代码是

using (StreamReader Data = new StreamReader("Telemetry_Data.txt")) //Reads Text From File
{
    String line = Data.ReadToEnd();
    Console.WriteLine(line);
    char[] SeprateData = { 'D', 'H', 'P', 'R', 'T', 'W', ':' };
    string[] stringData = line.Split(SeprateData);

    foreach (string ss in stringData)
    {
        Console.WriteLine(ss);
    }

1 个答案:

答案 0 :(得分:2)

这有点严重,但应该让你走上正确的道路。

var humidity = Regex.Matches(line, "H:(?<humidity>[0-9]+?):").Cast<Match>().ToArray().Average(x=>Convert.ToInt32(x.Groups["humidity"].Value));

我注意到您的数据集有30个日期,但只有14个湿度读数