Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to page an array using LINQ?

If I have an array like this :

string[] mobile_numbers = plst.Where(r => !string.IsNullOrEmpty(r.Mobile))
                                          .Select(r => r.Mobile.ToString())
                                          .ToArray();

I want to paging this array and loop according to those pages .

Say the array count is 400 and i wanna to take the first 20 then the second 20 and so on until the end of array to process each 20 item .

How to do this with linq ? .

like image 502
Anyname Donotcare Avatar asked Nov 30 '22 03:11

Anyname Donotcare


1 Answers

Use Skip and Take methods for paging (but keep in mind that it will iterate collection for each page you are going to take):

int pageSize = 20;
int pageNumber = 2;
var result = mobile_numbers.Skip(pageNumber * pageSize).Take(pageSize);

If you need just split array on 'pages' then consider to use MoreLinq (available from NuGet) Batch method:

var pages = mobile_numbers.Batch(pageSize);

If you don't want to use whole library, then take a look on Batch method implementation. Or use this extension method:

public static IEnumerable<IEnumerable<T>> Batch<T>(
     this IEnumerable<T> source, int size)
{
    T[] bucket = null;
    var count = 0;

    foreach (var item in source)
    {
        if (bucket == null)            
            bucket = new T[size];


        bucket[count++] = item;

        if (count != size)            
            continue;            

        yield return bucket;

        bucket = null;
        count = 0;
    }

    if (bucket != null && count > 0)
        yield return bucket.Take(count).ToArray();
}

Usage:

int pageSize = 20;
foreach(var page in mobile_numbers.Batch(pageSize))
{   
    foreach(var item in page)
       // use items
}
like image 92
Sergey Berezovskiy Avatar answered Dec 05 '22 02:12

Sergey Berezovskiy