C# Get every Nth element in a List

Let’s say you have the following list of objects:

[a1, b2, c3, d4, e5, f6, g7, h8, i9]

Now, say you want to grab every 3rd element inside this list, how would you do that? That is, you want the resulting list to be:

[c3,  f6,  i9]

Here’s a generic List extension algorithm that should help you do so (using C#):

        public static List<T> GetAllNthElements<T>(this List<T> list, int n)
        {
            List<T> result = new List<T>();
            for (int i = (n - 1); i < list.Count; i += n)
            {
                result.Add(list[i]);
            }

            return result;
        }

Explanation:

Let’s use our example from above, where we want every 3rd element inside that list. We’d call the method as:

var everyThirdElementList = theList.GetAllNthElements(3);

By passing it the Nth value as 3, the value of ‘i’ inside the for loop would start off as (n – 1) = (3 – 1) = 2. The second indexed item in the list will be grabbed, which, in this case is ‘c3’. Next, ‘i’ is incremented by n, so we get (i + n) = (2 + 3) = 5. This means the item in the fifth index is taken as well, which is ‘f6’. And so on, and so forth, until ‘i’ is greater than or equal to the list count.

In C#, simply add this under a List Extensions static class and import to whichever class you need this method in.

You way want to improve on this method by handling the following base cases:

  • If n is less than or equal to 0 (might not want to loop, this will cause errors)
  • If n is equal to 1 (you can just return the list that was given)