我有一个'双'值列表.我需要选择每第6条记录.这是一个坐标列表,我需要获得每第6个值的最小值和最大值.
坐标列表(样本):[2.1, 4.3, 1.0, 7.1, 10.6, 39.23, 0.5, ... ]
坐标坐标.
结果应如下所示:[x_min, y_min, z_min, x_max, y_max, z_max]
正好有6个坐标.
以下代码有效,但需要很长时间才能遍历所有坐标.我想用Linq代替(也许更快?)
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());
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?非常感谢!映入眼帘!
Mar*_*R-L 20
coordinateRange.Where( ( coordinate, index ) => (index + 1) % 6 == 0 );
Run Code Online (Sandbox Code Playgroud)
Webleeuw的回答是在此之前发布的,但恕我直言,使用索引作为参数而不是使用该IndexOf
方法更清楚.
这样的事情可能会有所帮助:
public static IEnumerable<T> Every<T>(this IEnumerable<T> source, int count)
{
int cnt = 0;
foreach(T item in source)
{
cnt++;
if (cnt == count)
{
cnt = 0;
yield return item;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
int[] list = new []{1,2,3,4,5,6,7,8,9,10,11,12,13};
foreach(int i in list.Every(3))
{ Console.WriteLine(i); }
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要跳过前几个条目,可以使用Skip()扩展方法:
foreach (int i in list.Skip(2).Every(6))
{ Console.WriteLine(i); }
Run Code Online (Sandbox Code Playgroud)
Where方法的重载使您可以直接使用索引:
coordinateRange.Where((c,i) => (i + 1) % 6 == 0);
Run Code Online (Sandbox Code Playgroud)