Is there a practical reason why the LINQ LongCount extension method has been added?

LINQ has 2 methods for counting enumerations: Countand LongCount. Almost the only difference between the two is that the first returns a int, and the second returns a long.

It is not clear why the second method was added. It seems that his only option would be to process enumerated elements from more than 2B elements. This seems like the wrong solution for me for several reasons:

  • Most BCL collections are supported by one-dimensional arrays that have lengths that are guaranteed to fit in int. Trying to pass, will increase OverflowException/ OutOfMemoryException.

  • LongCount- O (n), because it IEnumerableis lazy. If you list a 3B element, you call LongCounton it, and then you repeat it again (which you need if you want to use any values), you will add additional 3B iterations, which will be extremely slow and hide it from the developer.

  • Other LINQ operations, such as ToArray/ ToList, do not support enumerations with 2B + elements due to (1).

Am I missing something, or is there a more practical reason I LongCountadded it? Thank.

+4
source share
2 answers

, .

IQueryable; .

IQueryable<Foo> q = whatever;
long result1 = q.LongCount();
long result2 = q.AsEnumerable().LongCount();

. , , , .

, , ; , -, , .

+4

, (, COUNT_BIG COUNT sql-), . , , :

private static Random _r = new Random(1);
public static IEnumerable<BigInteger> RandomSequence(int upTo)
{
    while (true) {
        var next = _r.Next();
        if (next > upTo)
            yield break;
        yield return next;
    }
}

. , 2B . , , int.MaxValue - 5. :

RandomSequence(int.MaxValue - 5).Count();

( Count checked). LongCount !

RandomSequence(int.MaxValue - 5).LongCount();

, , , 1 Random.Next , int.MaxValue - 5 2583066202!

, , .

+2

Source: https://habr.com/ru/post/1660548/


All Articles