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

Related searches

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!

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.

How can I get every nth item from a List<T>?, GetNth(10) select element;. 2nd Edit: To make it even more LINQish from var i in Range(0, ((myList.Length-1)/n)+1) select list[n*i];. Get every Nth element from a list using a modulo expression. Put the elements in a new list. And: When the N is 2, we should select the first, third, and fifth

There is an overload of the Where method with lets you use the index directly:

coordinateRange.Where((c,i) => (i + 1) % 6 == 0);

C# Get Every Nth Element From List (Modulo), Get every Nth element from a list using a modulo expression. Put the Modulo: We use modulo division on the index (i) for each element in the list. When the And: When the N is 2, we should select the first, third, and fifth elements. So the� Below you can see formula has returned every nth value in column C. Note: - If you want to return every 3 rd value, then you just need to change in formula 3 at the place of 9, and formula will pick every 3 rd value from the range. This is the way we can use Excel formulas Index and row to get the Nth, 3 rd, 4 th etc. value from the range.

Something like this could help:

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;
        }
    }
}

You can use it like this:

    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); }

EDIT:

If you want to skip the first few entries, you can use the Skip() extension method:

foreach (int i in list.Skip(2).Every(6))
{ Console.WriteLine(i); }

Taking Every Nth Item from a Sequence, with a similar syntax that creates a sequence from every nth item in a source collection. in Language-Integrated Query's (LINQ) standard query operators. We can test the method by extracting some values from an array. As you are fetching data using Linq from the database, so the type of the variable would be IQueryable<>, and you can materialize the reuslt in to a List<> by forcing the query to be executed and results to be brought in the memory by calling ToList() method. So just change the last line from : return NPSData; to: return NPSData.ToList();

Any particular reason you want to use LINQ to do this?

Why not write a loop that steps with 6 increments each time and get access the value directly?

Filter C# loops with LINQ: efficient and easy � Kodify, Efficient C# loops: filter collections beforehand with LINQ methods Not every C# loop has to process every element from a collection (list, array, queue, Those can filter, select, group, and manipulate practically any data much like Perform a loop action every nth time with C#'s modulus operator ( % ). Your list will often be built out of numerous elements and components. Therefore, getting a single element, multiple elements, or a component out of it is not always straightforward. One way to select a component is using the numbered position of that component. For example, to "grab" the first component of shining_list you type . shining_list[[1]]

To find a faster solution start a profile!

Measure how long it takes for every step in your for loop and try to avoid the biggest bottleneck.

After making a second look at your code, it seems, your problem is that you run six times over your big list. So the time needed is always six times of the list size.

Instead you should run once over the whole list and put every item into the correct slot.

Just to make a performance test for yourself you should test these two approaches:

Sample class to hold data
public class Coordinates
{
    public double x1 { get; set; }
    public double x2 { get; set; }

    public double y1 { get; set; }
    public double y2 { get; set; }

    public double z1 { get; set; }
    public double z2 { get; set; }
}
Initializing of the value holder
Coordinates minCoordinates = new Coordinates();

//Cause we want to hold the minimum value, it will be initialized with
//value that is definitely greater or equal than the greatest in the list
minCoordinates.x1 = Double.MaxValue;
minCoordinates.x2 = Double.MaxValue;
minCoordinates.y1 = Double.MaxValue;
minCoordinates.y2 = Double.MaxValue;
minCoordinates.z1 = Double.MaxValue;
minCoordinates.z2 = Double.MaxValue;
Using a for loop if the index operator is O(1)
for (int i = 0; i < allCoordinates.Count; i++)
{
    switch (i % 6)
    {
        case 0:
            minCoordinates.x1 = Math.Min(minCoordinates.x1, allCoordinates[i]);
            break;
        case 1:
            minCoordinates.x2 = Math.Min(minCoordinates.x2, allCoordinates[i]);
            break;
        case 2:
            minCoordinates.y1 = Math.Min(minCoordinates.y1, allCoordinates[i]);
            break;
        case 3:
            minCoordinates.y2 = Math.Min(minCoordinates.y2, allCoordinates[i]);
            break;
        case 4:
            minCoordinates.z1 = Math.Min(minCoordinates.z1, allCoordinates[i]);
            break;
        case 5:
            minCoordinates.z2 = Math.Min(minCoordinates.z2, allCoordinates[i]);
            break;
    }
}
Using foreach if IEnumerator is O(1)
int count = 0;
foreach (var item in allCoordinates)
{
    switch (count % 6)
    {
        case 0:
            minCoordinates.x1 = Math.Min(minCoordinates.x1, item);
            break;
        case 1:
            minCoordinates.x2 = Math.Min(minCoordinates.x2, item);
            break;
        case 2:
            minCoordinates.y1 = Math.Min(minCoordinates.y1, item);
            break;
        case 3:
            minCoordinates.y2 = Math.Min(minCoordinates.y2, item);
            break;
        case 4:
            minCoordinates.z1 = Math.Min(minCoordinates.z1, item);
            break;
        case 5:
            minCoordinates.z2 = Math.Min(minCoordinates.z2, item);
            break;
    }
    count++;
}

Array Copy Every Nth Element, I thought about LINQ, but if I needed to use a loop to copy the results of everyNth I may aswell just copy the values between the arrays in the loop it's self. 0 0. When the select clause produces something other than a copy of the source element, the operation is called a projection. The use of projections to transform data is a powerful capability of LINQ query expressions. For more information, see Data Transformations with LINQ (C#) and select clause. See also. LINQ Query Expressions

I know, but you need to see the LINQ going on here. I'm selecting from Enumerable.Range() not the actual list, so anything changed while in that LINQ using select or whichever other method you can come up with, you can't really do anything with the List because you're not querying it directly.

c1:child 1 content c2:2 c3:element does not exist c4:element does not exist v1:child 1 content v2:2 v3:element does not exist v4:element does not exist In general, you can write simpler code when using casting to retrieve the contents of elements and attributes. See also. LINQ to XML Axes (C#)

Comments
  • Duplicate - stackoverflow.com/questions/682615/… - there is a discussion about the performance there too.
  • This doesn't make sense, what distinguishes x, y and z from the rest of the list? Why are you only looking at every 6th item in the list?
  • @ck Because the list is already sorted. Every point has 3 coordinates. And each 2 points belong together. Like this (x1,y1,z1)(x2,y2,z2)
  • Very interesting! Maybe a community wiki about uncommon overloads in the linq library is in order :-)
  • +1 for this idea, even when the OP probably looked for LINQ explicitly.
  • Very good, but I need to get every 6th element with variable start index. Something like: public static IEnumerable<T> Every<T>(this IEnumerable<T> source, int startIndex, int count) I think I'll manage that myself. Thanks!!
  • That's easy, using the Skip() method. See my extended answer.
  • It's a very huge list, and I hoped that Linq is faster than two 'for' loops.
  • why would linq necessarily be faster?
  • Maybe not necessarily but possibly?
  • it would be a for loop in linq to objects. no performance difference.
  • Why wouldn't he use LINQ? He can one-line anything he needs.