将行数据从LINQ中的分组数据转换为列

时间:2018-11-20 16:46:39

标签: c# linq

我正在读取一个csv文件。

数据未按任何顺序排序。我已经使用以下代码读取了文件

List<LatencyData> latencys = new List<LatencyData>();
        using (var reader = new StreamReader(filePath))
        {

            LatencyData latencyData = null;
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(';');
                var row = values[0].Split(',');


                latencyData = new LatencyData
                {
                    TimeStamp = (row[0] + "000"),
                    Prefix = row[1],
                    Uplink = row[2],
                    Latency = row[3]
                };

                latencys.Add(latencyData);
            }
        }

下一步是根据时间戳分组。

var grouped = latencys.GroupBy(item => item.TimeStamp);

在分组后看起来像这样。

enter image description here

现在我想将数据转换为这种格式

timeStamp  Latency0 Latency1 Latency2 Latency3 Latency4
1541030400  198      267.67   263      null      198

为此我用了这部分。

var transformed = grouped.Select(g => new
        {
            Hubs = g.Select(hub => new
            {
                stamp = g.Key,
                Latency0 = g.Where(item => item.Uplink == "0").Select(data => data.Latency),
                Latency1 = g.Where(item => item.Uplink == "1").Select(data => data.Latency),
                Latency2 = g.Where(item => item.Uplink == "2").Select(data => data.Latency),
                Latency3 = g.Where(item => item.Uplink == "3").Select(data => data.Latency),
                Latency4 = g.Where(item => item.Uplink == "4").Select(data => data.Latency),
            })
        }); 

结果不正确,并且有许多行返回相同的值。每个键只能有一行

timeStamp  Latency0 Latency1 Latency2 Latency3 Latency4
1541030400  198      267.67   263      null      198

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

您快到了。但是,您可能希望为每个延迟返回一个而不是对象列表:

var transformed = grouped.Select(g => new
{
    Hubs = g.Select(hub => new
    {
       stamp = g.Key,
       Latency0 = g.FirstOrDefault(item => item.Uplink == "0")?.Latency,
       Latency1 = g.FirstOrDefault(item => item.Uplink == "1")?.Latency,
       Latency2 = g.FirstOrDefault(item => item.Uplink == "2")?.Latency,
       Latency3 = g.FirstOrDefault(item => item.Uplink == "3")?.Latency,
       Latency4 = g.FirstOrDefault(item => item.Uplink == "4")?.Latency,
    })
});