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

Time:10-27

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

CodePudding user response:

You can use this method for your question.

List<int> sequence = new List<int>() { 10, 7, 10, 1, 10, 5, 10, 8 , 11 , 50 };
for (int i = 0; i < sequence.Count-1; i  )
{
   var lists= sequence.Skip(i).Take(3).ToList();
   foreach (var x in lists)
   {
     Console.Write(x);
   }
   Console.WriteLine();
}

Or You can use this code Linq

List<int> sequence = new List<int>() { 10, 7, 10, 1, 10, 5, 10, 8 , 11 , 50 };
for (int i = 0; i < sequence.Count - 1; i  )
{
  sequence.Skip(i).Take(3).ToList().ForEach(x => Console.Write(x));
  Console.WriteLine();
}

CodePudding user response:

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(1).Take(3))
    // If for further usage it makes sense to materialize each subset
    //.Select(i => sequence.Skip(1).Take(3).ToList())
    .ToList();
  • Related