如何根据其他元素从集合中检索元素?

时间:2017-08-05 13:39:44

标签: c# collections streamreader openfiledialog

我正在阅读一些txt文件。 我正在阅读每一行,通过最终添加到集合来分割和创建对象。

示例文件内容:

  

记录1,时间,摄氏度(°C),高报警,低报警,湿度(%rh),露水   点(°C),序列号
  1,02 / 06/2017 2017:26:30,19.5,32.0,7.0,64.0,12.5,11211222
  2,02 / 06/2017 2017:31:30,21.0,32.0,7.0,54.5,11.4
  3,02 / 06/2017 2017 09:36:30,20.5,32.0,7.0,54.5,11.0

List<MagModel> Records = new List<MagModel>();

using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text 
File|*.txt", Multiselect = true })
{
    ofd.InitialDirectory = HelperClass.GetDirectory;

    if (ofd.ShowDialog() == DialogResult.OK)
    {
        foreach (string file in ofd.FileNames)
        {
            using (StreamReader reader = new StreamReader(file))
            {
                reader.ReadLine();
                if (file.Contains("Record1"))
                {
                    var lines = from line in reader.Lines()
                                where !string.IsNullOrEmpty(line)
                                select line;

                    foreach (var line in lines)
                    {
                        var result = line.Split(',');

                        MagModel model1 = new MagModel();

                        model1.magazine = "Record1";                                   
                        model1.date = result[1];
                        model1.temp = Convert.ToDouble(result[2]);
                        model1.humidity = Convert.ToDouble(result[5]);
                        Records.Add(model1);

                    }

                    MaxMinTemperature.maxTemp = Records.Max(r => r.temp);
                    MaxMinTemperature.minTemp = Records.Min(r => r.temp);
                }
            }
        }
    }
}

然后我发现集合中的最高和最低温度(示例中为21.0和19.5):

MaxMinTemperature.maxTemp = Records.Max(r => r.temp);
MaxMinTemperature.minTemp = Records.Min(r => r.temp);

如何找到收集最高或/和最低温度的日期?

谢谢,

1 个答案:

答案 0 :(得分:0)

像这样定义你的模型:

public class MagModel
{
    public int Record1 { get; set; }
    public DateTime Time { get; set; }
    public double Celsius { get; set; }
    public double HighAlarm { get; set; }
    public double LowAlarm { get; set; }
    public double Humidity { get; set; }
    public double DewPoint { get; set; }
    public string SerialNumber { get; set; }
}

然后编写单独的解析方法:

public static IEnumerable<MagModel> ParseFile(string filename)
{
    // put your parsing here
}

现在很容易获得最高和最低温度的日期:

var input = ParseFile("input.csv");
var orderByCelsius = input.OrderBy(m => m.Celsius).ToArray();
var minTemperatureDate = orderByCelsius.FirstOrDefault()?.Time;
var maxTemperatureDate = orderByCelsius.LastOrDefault()?.Time;