Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select every 6th element from a list (using Linq) [duplicate]

Tags:

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!

like image 934
iDog Avatar asked Mar 16 '10 11:03

iDog


People also ask

How do I find duplicate records in Linq?

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) .

How do you get the second element in a list?

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.


1 Answers

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.

like image 131
Martin R-L Avatar answered Sep 19 '22 13:09

Martin R-L