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!

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
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
jimbad