wpf 2集合在datagrid中

时间:2014-02-17 15:13:17

标签: c# wpf collections wpfdatagrid

我有2个集合在另一个中,像这样,

public class Meter
    {
        public string MeterID { get; set; }
        public List<Data> data { get; set; }
    }

 public class Data
    {
        public string Time { get; set; }
        public int Signal { get; set; }
    }

我从这样的txt文件中读取它,

    public static void LoadMeterListFromFile(List<FileInfo> fileList)
    {
        foreach (FileInfo fi in fileList)
        {
            foreach (var line in File.ReadAllLines(fi.FullName))
            {
                var columns = line.Split(';');                      

                string MeterID = columns[1];

                if (!meters.ContainsKey(MeterID))
                {
                    meters.Add(MeterID, new Meter() { MeterID = MeterID, data = new List<Data>() });
                }
                Data d = new Data
             {
                 TimeStamp = columns[0],
                 Signal = Convert.ToInt32(columns[2].Replace("SignalStrength=", "")),

             };
                meters[MeterID].data.Add(d);
            }
        }
    }

如何在wpf数据网格中显示两个集合,最好是由MeterID分组?

1 个答案:

答案 0 :(得分:0)

您应该考虑更改读取数据的方式,并将MeterID添加到类Data。

public static void LoadMeterListFromFile(List<FileInfo> fileList)
{
    foreach (FileInfo fi in fileList)
    {
        foreach (var line in File.ReadAllLines(fi.FullName))
        {
            var columns = line.Split(';');
            string meterID= columns[1];

            if (!meters.ContainsKey(MeterID))
            {
                meters.Add(meterID, new Meter() { MeterID = meterID, data = new List<Data>() });
            }
            Data d = new Data
            {
                MeterID = meterID,
                TimeStamp = columns[0],
                Signal = Convert.ToInt32(columns[2].Replace("SignalStrength=", ""))
            };
            meters[MeterID].data.Add(d);
        }
    }
}

然后,按MeterID对结果进行分组并将它们添加到DataGrid:

public MyForm()
{
    InitializeComponent();

    // Get meters list

    var result = new List<Data>();
    foreach(var m in meters)
        result.AddRange(m.data);

    // the records should be grouped already, but to be sure you can use linq
    result.GroupBy(d => d.MeterID);

    // now add data to data grid
    BindingList<Data> data = new BindingList<Data>(result);
    dataGridView1.DataSource = data;