Linq to SQL-按问题排序 [英] Linq to SQL - Order by issue
问题描述
另一个分配块!
基本上,问题是我无法让输出按降序对价格进行排序,而又无法将其按国家/地区分组.
Basically the problem is that I can't get my output to order the price in a descending order while keeping it grouped by Country.
我知道这可能很简单,但我似乎无法理解.
I know it's probably something so simple but I just can't seem to get it.
有解决方案吗?
谢谢!
这里是一个问题: "6.允许用户按国家/地区降序查看排名前五位的畅销产品. (10分)"
Here is the question: "6. Allow the user view the top five selling products in descending order grouped by country. (10 marks)"
这是我的代码:
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var q6 = (from t in northwind.Products
orderby t.UnitPrice descending
join o in northwind.Suppliers on t.SupplierID equals o.SupplierID
group t.UnitPrice by new {o.Country, t.UnitPrice} into grouped
select new
{
Output = grouped.Key
}).Take(5);
lbxTop5.ItemsSource = q6;
}
推荐答案
"6.允许用户按国家/地区降序查看排名前五位的畅销产品.(10分)"
"6. Allow the user view the top five selling products in descending order grouped by country. (10 marks)"
我可以用两种方式阅读.
I could read that two ways.
A)获取最畅销的五种产品,按国家对这五种产品进行分组. 或者 B)对于每个国家/地区,最畅销的五个产品是什么?
A) Get the top five selling products, group those 5 products by country. OR B) For each country, what are the top five selling products?
我认为B更有意义,所以我会做到这一点.
I think B makes more sense, so I'll do that one.
另外-什么是最畅销的产品?这个国家和它有什么关系?我认为客户所在国家/地区比供应商所在国家/地区更为重要.另外-我认为OrderDetails中的数量可以告诉我哪些产品最畅销.注意:您的讲师可能会提出除我以外的其他想法,因此使用这些假设后果自负.
Also - what is a top selling product? and how is the country related to it? I think that the Customer's country matters more than the Supplier's. Also - I think that Quantity in the OrderDetails can tell me which products are top selling. Note: your instructor may have other ideas than I do, so use these assumptions at your own peril.
from c in northwind.Customers
from o in c.Orders //all froms except first are calls to SelectMany (one to many)
from od in o.OrderDetails //navigational properties -> no need to write explicit joins
let p = od.Product // now we go many to one, so we don't need SelectMany
group od
by new {c.Country, Product = p } //anon grouping key
into productGroup
let country = productGroup.Key.Country
let product = productGroup.Key.Product
let quantity = productGroup.Sum(od2 => od2.Quantity)
group new {Product = product, Quantity = quantity} //anon group elements
by country
into countryGroup
select new {
Country = countryGroup.Key,
Summaries = countryGroup
.OrderByDescending(summary => summary.Quantity)
.ThenBy(summary => summary.Product.ProductId) //tiebreaker
.Take(5)
.ToList()
}
这篇关于Linq to SQL-按问题排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!