Search code examples
c#listlinqfunctional-programmingreactive-programming

How Select n separate list<int> with overlap from one list<int> in functional way in C#


In C# I have a list like this:

var sequence = new List<int> { 10, 7, 10, 1, 10, 5, 10, 8 , 11 , 50 };

I want to create 10 separate list by iterating through the sequence and in each iteration select three element instead of one element.

Iterating though list with overlap

I wrote code below for this purpose but it has flaws and must be a better way of doing that:

var sequence = new List<int> { 10, 7, 10, 1, 10, 5, 10, 8 , 11 , 50 };
var lists = Enumerable.Range(0, 10)
        .Select(i =>
        {
            var list = sequence.GetRange(i, 3);
            return list;
        }).ToList();

P.S.: ‌Functional way I mean somthing like this:

var lists = Sequence.Window(sourceSafed.Skip(1)).....Select(window => window.Take(3))......ToList();

Solution

  • As the comments already stated there is nothing really wrong with your code. To make it look more LINQish you could write:

    var sequence = new List<int> { 10, 7, 10, 1, 10, 5, 10, 8 , 11 , 50 };
    var lists = Enumerable.Range(0, 10)
        .Select(i => sequence.Skip(i).Take(3))
        // If for further usage it makes sense to materialize each subset
        //.Select(i => sequence.Skip(i).Take(3).ToList())
        .ToList();