Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a Linq Dynamic Query result as a custom class?

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!

like image 644
Zachary Scott Avatar asked Mar 29 '10 06:03

Zachary Scott


1 Answers

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.

like image 160
casperOne Avatar answered Oct 24 '22 04:10

casperOne