如何从列表中选择第6个元素(使用Linq) [英] How do I select every 6th element from a list (using Linq)

查看:69
本文介绍了如何从列表中选择第6个元素(使用Linq)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双精度"值列表.我需要选择每6条记录.这是一个坐标列表,我需要在其中获取每个第6个值的最小值和最大值.

I've got a list of 'double' values. I need to select every 6th record. It's a list of coordinates, where I need to get the minimum and maximum value of every 6th value.

坐标列表(样本):[2.1, 4.3, 1.0, 7.1, 10.6, 39.23, 0.5, ... ] 带有数百个坐标.

List of coordinates (sample): [2.1, 4.3, 1.0, 7.1, 10.6, 39.23, 0.5, ... ] with hundrets of coordinates.

结果应如下所示:[x_min, y_min, z_min, x_max, y_max, z_max] 精确地有6个坐标.

Result should look like: [x_min, y_min, z_min, x_max, y_max, z_max] with exactly 6 coordinates.

以下代码可以工作,但是要遍历所有坐标都需要很长时间.我想改用Linq(也许更快?)

Following code works, but it takes to long to iterate over all coordinates. I'd like to use Linq instead (maybe faster?)

for (int i = 0; i < 6; i++)
{
    List<double> coordinateRange = new List<double>();

    for (int j = i; j < allCoordinates.Count(); j = j + 6)
        coordinateRange.Add(allCoordinates[j]);

    if (i < 3) boundingBox.Add(coordinateRange.Min());
    else boundingBox.Add(coordinateRange.Max());
}

有什么建议吗? 非常感谢!问候!

Any suggestions? Many thanks! Greets!

推荐答案

coordinateRange.Where( ( coordinate, index ) => (index + 1) % 6 == 0 );

Webleeuw的答案发布在此之前,但是恕我直言,使用索引作为参数而不是使用IndexOf方法更为清楚.

The answer from Webleeuw was posted prior to this one, but IMHO it's clearer to use the index as an argument instead of using the IndexOf method.

这篇关于如何从列表中选择第6个元素(使用Linq)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆