我有几个来自传感器的数据枚举

time_elapsed,speed_x,speed_y,speed_z,海拔,纬度,经度…

每个列表具有相同数量的元素。

我想将所有列表的数据合并为一系列Status项目。

class Status
{
    public int TimeElapsed {get; set; }
    public double SpeedX {get; set; }
    public double SpeedY {get; set; }
    public double SpeedZ {get; set; }
   ...
}


我考虑过使用Enumerable.Zip方法,但它看起来确实很麻烦:

var statuses = time_elapsed
    .Zip(speed_x, (a, b) => new { a,  b})
    .Zip(speed_y, (c, d) => new { c,  d})
    .Zip(speed_z, (e, f) => new { e , f})
    .Select(x => new Status
    {
        Time = x.e.c.a,
        SpeedX = x.e.c.b,
        SpeedY = x.e.d,
        SpeedZ = x.f
        // ...
    });


如您所见,它来自所有这些匿名类型的可读性。

有没有更好的方法来做到这一点而又不失头呢?

最佳答案

您可以在此处执行的操作不多,但是可以提高可读性并删除一种匿名类型:

var statuses = time_elapsed
    .Zip(speed_x, (time, speedX) => new {time, speedX})
    .Zip(speed_y, (x, speedY) => new {x.time, x.speedX, speedY})
    .Zip(speed_z, (x, speedZ) => new Status
    {
        TimeElapsed = x.time,
        SpeedX = x.speedX,
        SpeedY = x.speedY,
        SpeedZ = speedZ
    });


您也可以使用这种方法:

int minSize = new IList[] {time_elapsed, speed_x, speed_y, speed_z}.Min(c => c.Count);
IEnumerable<Status> statuses = Enumerable.Range(0, minSize)
    .Select(i => new Status
    {
        TimeElapsed = time_elapsed[i],
        SpeedX = speed_x[i],
        SpeedY = speed_y[i],
        SpeedZ = speed_z[i],
    });

关于c# - 如何处理多个Enumerable.Zip调用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52705392/

10-13 08:05