简体   繁体   中英

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); 
} 

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM