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.
List of coordinates (sample): [2.1, 4.3, 1.0, 7.1, 10.6, 39.23, 0.5, ... ]
with hundrets of coordinates.
Result should look like: [x_min, y_min, z_min, x_max, y_max, z_max]
with exactly 6 coordinates.
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!
The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to: var query = lst. GroupBy(x => x) .
Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.
coordinateRange.Where( ( coordinate, index ) => (index + 1) % 6 == 0 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With