Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use Long type for Skip in Linq

Tags:

c#

linq

How I can use long type (Int64) with Skip in Linq. It support only Int32.

dataContext.Persons.Skip(LongNumber);
like image 660
Pavel Jedlicka Avatar asked Dec 25 '22 15:12

Pavel Jedlicka


2 Answers

You can use a while loop:

// Some init
List<Person> persons = new List<Person>();
List<Person> resultList = persons;
long bigNumber = 3 * (long)int.MaxValue + 12;

while (bigNumber > int.MaxValue)
{
    resultList = resultList.Skip(int.MaxValue).ToList();
    bigNumber -= int.MaxValue;
}
resultList = resultList.Skip(int.MaxValue).ToList();
// Then what do what you want with this result list

But does your collection have more than int.MaxValue entries?

like image 183
Thomas Ayoub Avatar answered Dec 27 '22 17:12

Thomas Ayoub


The following extension method BigSkip allows skipping more than the Int32.MaxValue maximum value of LINQ's Skip method by calling the method multiple times until the long value has been reached. This method has the advantage of not causing iteration over the collection prematurely.

example usage

bigCollection.BigSkip(howMany: int.MaxValue + 1l)

method

using System;
using System.Collections.Generic;
using System.Linq;

static public class LinqExtensions
{
    static public IEnumerable<T> BigSkip<T>(this IEnumerable<T> items, long howMany)
        => BigSkip(items, Int32.MaxValue, howMany);

    internal static IEnumerable<T> BigSkip<T>(this IEnumerable<T> items, int segmentSize, long howMany)
    {
        long segmentCount = Math.DivRem(howMany, segmentSize,
            out long remainder);

        for (long i = 0; i < segmentCount; i += 1)
            items = items.Skip(segmentSize);

        if (remainder != 0)
            items = items.Skip((int)remainder);

        return items;
    }

}

The method has been split into two: the internal overload is for convenience allowing a smaller segment size to be specified than Int32.MaxValue to make it unit testable on a smaller scale.

bonus

Replace Skip with Take to make a BigTake method; this same extension method pattern can be used to extend the reach of other LINQ methods.

like image 39
John K Avatar answered Dec 27 '22 18:12

John K