Search code examples
c#linq.net-corepagination

Applying pagination on subcollection


How to apply pagination on subcollection? Below is the structure. The requirement is when I set page limit to 10, if the details in SampleDataSet have more than 10 records, then the first 10 records only need to show. So when I apply pagination like below

listSampleDataSet = listSampleDataSet .Skip(pageIndex).Take(pageSize);

It will return 10 SampleDataSet how to apply pagination so that it will return only one SampleDataSet because Details collection in it got more than 10 records.

Example:

public class SampleDataSet
{
   int id {get;set;}
   int name {get;set;}
   List<DetailsDataSet> Details {get;set;}
}

 List<SampleDataSet> listSampleDataSet = new List<SampleDataSet>();
listSampleDataSet = listSampleDataSet .Skip(pageIndex).Take(pageSize);

It will return 10 SampleDataSet, which is correct, since pagination applied on the main collection. How to apply pagination so that it will return only one SampleDataSet because Details collection in it got more than 10 records?


Solution

  • In case you have access to the root collection of DetailsDataSet you can:

    1. Use join instead of navigation properties
    2. Change the direction of your getting data: means you should have DetailsDataSet as a main collection filtered by parrent id (in case you are showing the specific SampleDataSet object) and applied paging.

    Otherwise move the paging functionality into the SampleDataSet create a function/property that would gives you next page of details (and previous as well) with storing of the state in the object itself

    public class SampleDataSet
    {
       public int id { get; set; }
       public int name { get; set; }
       public List<DetailsDataSet> Details { get; set; }
    
       private int page = 0;
       private int pageSize = 10;
    
       public bool HasNextPage() => Details.Count > pageSize * (page + 1);   
       public IEnumerable<DetailsDataSet> GetNextPage() => Details.Skip(pageSize * page++).Take(pageSize);
        // etc...
    }