Question

Normally, I do this:

var a = from   p in db.Products
        where  p.ProductType == "Tee Shirt"
        group  p by p.ProductColor into g
        select new Category { 
               PropertyType = g.Key,
               Count = g.Count() }

But I have code like this:

var a = Products
        .Where("ProductType == @0", "Tee Shirt")
        .GroupBy("ProductColor", "it")
        .Select("new ( Key, it.Count() as int )");

What syntax could I alter to produce identical results, i.e., how do I do a projection of Category from the second Linq statement?

I know in both that g and it are the same and represent the entire table record, and that I am pulling the entire record in just to do a count. I need to fix that too. Edit: Marcelo Cantos pointed out that Linq is smart enough to not pull unnecessary data. Thanks!

Was it helpful?

Solution

Why would you have to do it at all? Since you still have all of the information after the GroupBy call, you can easily do this:

var a = Products
        .Where("ProductType == @0", "Tee Shirt")
        .GroupBy("ProductColor", "it")
        .Select(c => new Category { 
            PropertyType = g.Key, Count = g.Count() 
        });

The type of Products should still flow through and be accessible and the regular groupings/filtering shouldn't mutate the type that is flowing through the extension methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top