views:

333

answers:

1

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!

+1  A: 

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.

casperOne
I would be surprised if the result of a Dynamic Query would have anything but a Dynamic Query Select method available, taking only a string parameter, not a lambda. This is of course unless I am missing something obvious.
Dr. Zim
In other words, after the .GroupBy() the only select available is .Select which is the Dynamic Query version (minus the Lambda).
Dr. Zim
The specific error I get in doing that is "Cannot convert lambda expression to type 'string' because it is not a delegate type. My code was var a = Products.GroupBy("ProductColor", "it").Select(c => new { name = ((Products)c).ProductName });However, if I use a nested foreach( IGrouping<string,Products> b in a) { foreach ( Products c in b ) { // create a List manually }}, then this works pretty well. It extracts the values and sets them in a different memory variable, but at least it's a way.
Dr. Zim
If you know a way to project a's values in a separate Linq query as a particular type, I will gladly mark your answer as green.
Dr. Zim