Craig Shearer
Craig Shearer

Reputation: 14541

LINQ grouping in C#

I'm puzzled. I copied this code from the Microsoft LINQ examples site, but can't get it to compile.

I want to do something similar, but it says it cannot resolve symbol minPrice, and a bunch of other errors. What gives?

public void Linq84() { 
   List products = GetProductList();

   var categories = 
      from p in products 
      group p by p.Category into g 
      from minPrice = g.Group.Min(p => p.UnitPrice) 
      select new {Category = g.Key, CheapestProducts = g.Group.Where(p => p.UnitPrice == minPrice)};

   ObjectDumper.Write(categories, 1); 
} 

Upvotes: 2

Views: 613

Answers (1)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828090

I think that the query has some typos, or was made in the early stages of Linq.

I'll rewrite it as this:

var categories = from p in products
                 group p by p.Category into g
                   let  minPrice = g.Min(p => p.UnitPrice)
                 select new {
                              Category = g.Key,
                              CheapestProducts = g.Where(p => p.UnitPrice == minPrice)
                            };

BTW, as good learning resources I highly recommend you LinqPad which is a great tool and HookedToLinq.

Upvotes: 7

Related Questions