👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using LINQ Chunk to Split Data

Using LINQ Chunk to Split Data

LINQ

26 Articles

Improve

In this article, let's learn about how to use Chunk in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Using LINQ Distinct to Select Specific Data in Collections.

Table of Contents

  1. Introduction
  2. Split collections into smaller collections using Chunk
  3. Summary

Introduction

We can split collection into small collection of arrays using LINQ. We're going to use Chunk() method. Let's take a look at each of these methods and how they work.

Split collections into smaller collections using Chunk

Let's partition data into other format. We can split our (Larger) Collection into array of smaller collections using Chunk() method. This will give list of data array. What Chunk(n) does is that it takes first n items from collection and build an array with that items and put them into first item of our final list. Then it takes second n items from collection build an array and put it into second item of our final list forming collection of collections.

Code Sample - LINQ Chunk

Demo - LINQ Chunk Clause Demo

Let's try LINQ Chunk

  • We have Product class with following properties - Id, Name, Color, Price, Size
  • Enter the number of products you would like to list.
  • Click on Chunk Button
  • Click on reset to try other combination
Id Name Color Price Size
1 Shirt Black 1000 18
2 Shirt Red 1500 28
3 Shirt Black 2000 38
4 Shirt Red 2500 48
5 Shirt Brown 3000 58
6 Shirt White 3500 68

Summary

In this article we learn't how to split data within collection using Chunk. This can be used for pagination for small in-memory collections to improve user experience. All these can be used with any IEnumerable or IQueryable types.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • LINQ
  • Chunk
  • Split