我有一些Product结构,在那里我有,例如,ProductId和ProductVariantId.每种产品都可以有许多变体.例如,Product1可以有变量1和2. Product2可以有变量1,2和3,所以我有以下列表:
ProductId: 1, ProductVariantId 1
ProductId: 1, ProductVariantId 2
ProductId: 2, ProductVariantId 1
ProductId: 2, ProductVariantId 2
ProductId: 2, ProductVariantId 3
Run Code Online (Sandbox Code Playgroud)
我想要做的是获取productId只有一个给定的变体.当productId没有给定变体时,我的机制应该取最大值.
所以给定变体的示例3应如下所示:
ProductId: 1, ProductVariantId 2 (maximum)
ProductId: 2, ProductVariantId 3
Run Code Online (Sandbox Code Playgroud)
我试着这样做:
products.ToList().Where(x => x.ProductVariant == givenProductVariant)
Run Code Online (Sandbox Code Playgroud)
我想补充的是某种数据库distinct上productId,并获得最大.
我可以请求帮助吗?
你可以使用这种GroupBy方法,通过一个boolif ProductVariantId = 3来代替组,或者通过ProductVariantId desc:
int productVariantId = 3;
var query = products.GroupBy(p => p.ProductId)
.Select(g => g.OrderByDescending(p => p.ProductVariantId == productVariantId)
.ThenByDescending(p => p.ProductVariantId)
.First()); // First ensures that we get one row per group
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |