[英]LINQ (to Entities) Query with Sorting and Grouping
我似乎需要一个LINQ(针对MS SQL Server的实体)查询,有点麻烦。
我的架构如下所示:
我的任务是显示特定ProductItem
所有ProductPricing
行,按ProductPricing.EffectiveDate
排序,并按ProductPricing.CompaniesId
分组。
此外,我需要按ProductItemCompanies.SortOrder
来订购组。
请注意, ProductPricing.CompaniesId
可以为null
,并且CompaniesId
为null
所有ProductPricing
行都需要分组为单个组,并放置在所有其他组之前。
我已经进行了无数次尝试,但是对于LINQ联接或分组的理解还不够清楚。 我当前的代码看起来像这样,但是它既不正确,甚至无法编译。
(请注意, DefaultProductItem
是我正在为其显示ProductPricing
的ProductItems
。)
var vendors = from pp in this.DefaultProductItem.ProductPricings
orderby pp.EffectiveDate
join pic in this.DefaultProductItem.ProductItemCompanies on pic.CompanyId equals pp.CompanyId &&
pic.ProductItemId equals this.DefaultProductItem.Id
group pp by pp into v
select v;
更新:
在Tim.Tang的帮助下,我运行了以下查询:
var vendors = from pp in DefaultProductItem.ProductPricings
join pic in DefaultProductItem.ProductItemCompanies
on pp.CompanyId equals pic.CompanyId into left
from pic in left.DefaultIfEmpty()
orderby pp.EffectiveDate descending, pic == null ? -1 : pic.SortOrder
group pp by pp.CompanyId into v
select v;
这接近了,但是不会按ProductItemCompanies.SortOrder
对结果组进行排序。 尽管上面的查询确实按此值排序,但这似乎不会影响这些组。
我知道我可以很容易地对事实进行排序,但是我希望将其作为原始查询的一部分,以提高效率。
这是我的建议,希望可以帮到您:
var vendors = from pp in this.DefaultProductItem.ProductPricings
join pic in this.DefaultProductItem.ProductItemCompanies.Where(x=>x.ProductItemId == this.DefaultProductItem.Id)
on pp.CompanyId equals pic.CompanyIdinto left
from pic in left.DefalutIfEmpty()
orderby pp.EffectiveDate, pic==null?0:pic.SortOrder //sort order is INT?
group pp by pp.CompaniesId into v
select v;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.