我想抓住10个最有序的产品.我的表看起来与此类似:
ProductProductID |产品名称
OrderedProductProductID |订单ID
OrderOrderID | DateOrdered
目前我有以下内容:
return (from product in db.Products from orderedProduct in db.OrderedProducts where orderedProduct.ProductID == product.ProductID select product).OrderByDescending(???).Distinct().Take(10);
解决方法
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个项目,每个项目包含product对象,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>.