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!

Zachary Scott
  • 20,968
  • 35
  • 123
  • 205

1 Answers1

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.

casperOne
  • 73,706
  • 19
  • 184
  • 253
  • 1
    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. – Zachary Scott Mar 30 '10 at 03:07
  • In other words, after the .GroupBy() the only select available is .Select which is the Dynamic Query version (minus the Lambda). – Zachary Scott Mar 30 '10 at 03:08
  • 1
    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 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. – Zachary Scott Apr 01 '10 at 04:47
  • 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. – Zachary Scott Apr 01 '10 at 04:49