How I can use long type (Int64) with Skip in Linq. It support only Int32.
dataContext.Persons.Skip(LongNumber);
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With