Search code examples
c#entity-frameworklinqcode-first

Is there a possibility to take 100 records then other 100 record from database table using LinQ and Take()


Using Code First, Oracle database I need to select first 100 recors if there are a big amount of data, but I also need to have a possibility to get the rest records, so how to take next 100 recors starting from 101?

If there a possibility to do it using Linq Take()?

List<int> myList = new List<int>();
List<int> newList = new List<int>();

myList = DBContext.MyTable.Where(x=>x.ID == someParam).Select(x=>x.ID).toList();
int recodCount = myList.Count();

if (recodCount > 1000)
{
    newList.AddRange(myList.Take(100));
}
else
{
    newList.AddRange(myList);
}

Solution

  • I suppose you need pagination you need to define pageIndex and pageSize

    myList = DBContext.MyTable
                      .Where(x=>x.ID == someParam)
                      .Skip((pageIndex - 1) * pageSize)
                      .Take(pageSize);
    

    But if you want only to skip by 100 what you are missing is Skip: Enumerable.Skip Method.

    Like Tim said don't call ToList() in the begging this will select everything in the memory. Also don't call Count() to check if(count > 100). You should do it with : if(myList.Skip(number).Any()) this will be true if your collection has more records than number.