How to get Count in GroupBy

I tried to translate the very common sql query

Select Category, count(*) as NumberOfProducts from Products group by Category

into linq syntax.

I was able to write it like this:

var orderGroups = from p in products group p by p.Category into g select new { Category = g.Key, NumberOfProducts = g.Count() };

Question: is there a O(1) way, to get the NumberOfProducts without using the Count()-Function running presumably O(n)

Thanks!




Answer this question

How to get Count in GroupBy

  • the redjinn

    Thanks for the answer which is absolutely correct for dlinq. But my question was more related to linq itself, so my "underlying server" is something that implements IEnumerable<T>.



  • Amit11

    Good Point! The "group by" returns a class of type Grouping which implements ICollection<T>, so Count() runs O(1).



  • jozeph

    It all depends on what implements IEnumerable<T>. If it's a collection, it's mostly just a read to a property as shows the source code of the Count query operator:

    public static int Count<T>(this IEnumerable<T> source)
    {
    if (source == null)
    throw Error.ArgumentNull("source");

    ICollection<T> collection = source as ICollection<T>;
    if (collection != null)
    return collection.Count;

    int count = 0;
    using (IEnumerator<T> e = source.GetEnumerator())
    {
    checked
    {
    while (e.MoveNext())
    count++;

    }
    }

    return count;
    }


  • iDhinesh

    Just remember, optimally don't care about the O() when using Linq, in theory the Linq provider interfaces will allow faster implementations to get plugged in if need be.
  • jimbad

    Depending on the underlying server, which in all of our cases at the moment, is SQL 2005 - Counting the number of rows in a group is actually a O(1) operation. It has a fixed cost because SQL has already retrieved the individual rows for the grouping clause itself. Retrieving the count of the rows retrieved is an ancillary, O(1) cost operation.


  • How to get Count in GroupBy