0

I got a list of data like bellow. Here I already added 50 demo items in list. Now I want to make a chunk of list splitted by 10 items in each chunk. How can I do it? I already tried like bellow using while loop and GroupBy but I am not getting idea what's the best way to do it? All I need is from this 50 items it should be make a new list which will GroupBy 10 items.

Model:

class Data
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public static List<Data> data { get; set; } = new List<Data>();
    }

Main Program:

class Program
{

    static void Main(string[] args)
    {
        for (int i = 0; i < 50; i++)//seeding 50 example data to global class
        {
            Data.data.Add(new Data
            {
                Id = i,
                Text = null,
            });
        }
    

        var chunkList = new List<Data>();//i need a chunk of list devided by 10 items in each chunk
        int count = 0;
        foreach (var item in Data.data)
        {
            do
            {
                chunkList.AddRange(chunkList.GroupBy(u => u.Id).Select(grp => grp.ToList()).ToList());//this logic is wrong
                count++;
            } while (count == 10);
            
        }


        Console.WriteLine("");
        
    }
Liakat Hossain
  • 1,288
  • 1
  • 13
  • 24
  • Does this answer your question ? https://stackoverflow.com/questions/13709626/split-an-ienumerablet-into-fixed-sized-chunks-return-an-ienumerableienumerab/13710023#13710023 Also check the link as duplicated – Quentin Grisel Feb 13 '21 at 16:43

1 Answers1

1

Here I found most easiest solution for my problem. I am using MoreLinq and using Batch as you can see bellow.

int size = 10;
var chunkList = Data.data.Batch(size);
Liakat Hossain
  • 1,288
  • 1
  • 13
  • 24
  • Even if a third party lib can do this for you, it doesn't really answer the question, nor does a link only answer which this basically amounts to. The algorithm is actually quite simple and I encourage you to still try and implement it yourself or by looking at the suggested duplicate. Solving yourself and/or understanding what the solution is goes a long way to helping not only the problem at hand but also giving you the tools to solve other problems that will undoubtedly present themselves to you in the future – pinkfloydx33 Feb 13 '21 at 17:33
  • You are right @pinkfloydx33 – Liakat Hossain Feb 13 '21 at 17:36