return (from product in db.Products
from orderedProduct in db.OrderedProducts
where orderedProduct.ProductID == product.ProductID
group orderedProduct by product into productGroups
select new
{
product = productGroups.Key,
numberOfOrders = productGroups.Count()
}
).OrderByDescending(x => x.numberOfOrders).Distinct().Take(10);
它會給你10個項目,每個項目包含產品對象和numberOfOrders整數。
編輯:
由於這將是作爲一個方法的返回值,因爲C#不允許返回一個匿名類型(還沒有..這個功能是在C#4.0),在轉換匿名類入類。
創建一個類你想回到
public class ProductOrders
{
public ProductOrders() {
}
public Product product { get; set; }
public int numberOfOrders { get; set; }
}
,並使用該查詢返回該類
return (from product in db.Products
from orderedProduct in db.OrderedProducts
where orderedProduct.ProductID == product.ProductID
group orderedProduct by product into productGroups
select new ProductOrders
{
product = productGroups.Key,
numberOfOrders = productGroups.Count()
}
).OrderByDescending(x => x.numberOfOrders).Distinct().Take(10);
返回值是現在式IEnumerable<ProductOrders>
的對象的類型。
你會發現這個問題非常有用: http://stackoverflow.com/questions/1322675/linq-keyword-search-with-orderby-relevance-based-on-count-linq-to-sql – 2009-09-07 00:42:56