tags:

views:

62

answers:

2

From the given Product List

List<Product> productList = new List<Product>();
productList.Add(new Product("P001", 34566.78M, "North"));
productList.Add(new Product("P004", 4566.78M, "East"));
productList.Add(new Product("P007", 14566.78M, "South"));

productList.Add(new Product("P010", 2456.178M, "South"));
productList.Add(new Product("P011", 341566.78M, "North"));
productList.Add(new Product("P006", 64566.878M, "East"));

productList.Add(new Product("P00188", 664566.78M, "East"));
productList.Add(new Product("P00111", 3444566.78M, "North"));
productList.Add(new Product("P00134", 3234566.78M, "South"));

How to select Top 2 Product (price based) from each region ?

I have written something like

var query = productList.OrderByDescending(p => p.ProductPrice).
 Take(2).GroupBy(r => r.Region);
+7  A: 

Group by region first, then within each group do the OrderBy/Take. For example:

var query = productList
   .GroupBy(r => r.Region)
   .Select(group => new { Region = group.Key,
                          Orders = group.OrderByDescending(p => p.ProductPrice)
                                        .Take(2) });
Jon Skeet
Jon skeet is always there for rescue! :)
A: 

It's not pretty and not terribly readable, but if you must do it in one statement, this will do the trick for you,

var q = productList.Select(pl => pl.Region)
                .Distinct()
                .ToList()
                .SelectMany(region => productList.Where(pl => pl.Region == region)
                                                 .OrderByDescending(pl => pl.ProductPrice)
                                                 .Take(2));

I'd recommend breaking it up for readability though.

mattdlong