-2

How to split List2 to 3 lists,

first list 4 items

second list 4 items

third list 2 items

public static class ListExtensions
{
    public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) 
    {
        return source
            .Select((x, i) => new { Index = i, Value = x })
            .GroupBy(x => x.Index / chunkSize)
            .Select(x => x.Select(v => v.Value).ToList())
            .ToList();
    }
}

double[][] x;
x = new double[10][];
   for (int ii = 0; ii < 10; ii++)
   {
         x[ii] = new double[4];
         for (int jj = 0; jj < 4; ++jj)
                 x[ii][jj] = 0.45;
   }

// Convert x matrix to list

 List<double[][]> List2= new List<double[][]>();
 List2.Add(x);

 List<double[][]> List1 = new List<double[][]>();

 List1 = ListExtensions.ChunkBy(List2, 3)[0]; // must be List of double[][]

 Console.Write(List1.Count );  // it should be 3
 Console.ReadLine();

List1 should includes 3 lists of double[][], but i have got one list,

List1.Count : 1

List1 shoulde be like this:

List1[0] = x[0],  x[1],  x[2],  x[3]

List1[1] = x[4],  x[5],  x[6],  x[7]

List2[2] = x[8],  x[9]
shdotcom
  • 125
  • 1
  • 1
  • 11
  • 1
    Possible duplicate of [Split a List into smaller lists of N size](https://stackoverflow.com/questions/11463734/split-a-list-into-smaller-lists-of-n-size) – Roman Koliada Dec 15 '17 at 09:28
  • @RomanKoliada No it is different, part of my answer from your link – shdotcom Dec 15 '17 at 09:30
  • This operation also called BATCH: https://stackoverflow.com/questions/13731796/create-batches-in-linq – eocron Dec 15 '17 at 09:31
  • @RomanKoliada which part of my answer is not correct? – shdotcom Dec 15 '17 at 09:32
  • @shdotcom How can `List1` contains 3 items if your original `List2` contains only one item? – Roman Koliada Dec 15 '17 at 09:33
  • Your list, 'List2' on which you are calling ChunkBy() has only 1 element. – Srinath Mandava Dec 15 '17 at 09:33
  • @RomanKoliada I have edited the question, would you please check it. – shdotcom Dec 15 '17 at 09:52
  • @shdotcom I guess I finally understand what you want but your `List1` must be of type `List` – Roman Koliada Dec 15 '17 at 10:55
  • @RomanKoliada , in my code I have double[][] x and I want to split it to List, the size of x is not constant, the number of arrays in each list also not constant, for example if i want two lists the output will be: List1[0] = x[0], x[1], x[2], x[3], x[4] List1[1] = x[5], x[6], x[7], x[8], x[9] List1 must be: List and i do not want to use skip take method – shdotcom Dec 15 '17 at 11:19

1 Answers1

1

I hope this is a function that you need:

List<double[][]> ChunkBy(double[][] x, int number){
    var result = new List<double[][]>();    
    int chunkSize = (int)Math.Ceiling(((double)x.GetLength(0))/number);
    for(int i = 0; i< number; i++){
        result.Add(x.Skip(chunkSize * i).Take(chunkSize).ToArray());    
    }

    return result;
}
Roman Koliada
  • 4,286
  • 2
  • 30
  • 59