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

1

6

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!

Huambo answered 29/3, 2010 at 6:33 Comment(2)
Have you verified that you are actually pulling the whole record? I don't know dynamic LINQ at all, but I don't see why it couldn't be just as smart about this as static LINQ-to-SQL.Tramline
I think Cantos is correct about how much it pulls.Huambo
N
2

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.

Nesselrode answered 29/3, 2010 at 17:24 Comment(4)
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.Huambo
In other words, after the .GroupBy() the only select available is .Select which is the Dynamic Query version (minus the Lambda).Huambo
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.Huambo
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.Huambo

© 2022 - 2024 — McMap. All rights reserved.