Every Nth item in a list
Today I was asked a straightforward question on how would you get every 4th element from an array of numbers starting at 1 - 11
I immediately thought oh I can do this in a functional fluent manner, but then I flubbed it up because I tried to do a Skip and Take combination which is more complicated than needs to be and doesn't work correctly
Something like this
Enumerable.Range(1, 11).Skip(z => z +3).Take(1);
Problem is that Skip
does not accept a function as it's input so this doesn't compile. :( :(
So you could then do it the old fashioned way of
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var items = new List<int>();
for (var index = 1; index < 11; index = index + 3)
{
items.Add(index);
}
Console.WriteLine(string.Join(",", items));
}
}
Output
1,4,7,10
However I don't like this approach because the input state is intertwined with the output
So, I drove home in my car and then made dinner and sipped some tea and then got the full picture that I need to adjust my filter condition i.e. add a Where
set operator to get the Nth element and so I looked at the Where documentation and the overload that lets you get the element and index is what I needed i.e. Where((element, index) => {})
and just like in JavaScript for Filter you can now do the proper list operation.
So
The generic way to represent the every Nth
item in list
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var range = Enumerable.Range(1, 10);
const int skip = 3;
Console.WriteLine(string.Join(",", range.EveryNth(skip)));
Console.WriteLine(string.Join(",", range.Reverse().EveryNth(skip)));
}
}
public static class EnumerableExtensions
{
public static IEnumerable<int> EveryNth(this IEnumerable<int> range, int skip = 1)
{
return (range ?? new List<int>() {}).Where((element, index) => index % skip == 0);
}
}
Output
1,4,7,10
10,7,4,1