C#LINQ Get List子集条件困难

use*_*344 0 c# linq list

我有一些Product结构,在那里我有,例如,ProductIdProductVariantId.每种产品都可以有许多变体.例如,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)

我想补充的是某种数据库distinctproductId,并获得最大.

我可以请求帮助吗?

Tim*_*ter 6

你可以使用这种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)