C# 具有困难条件的C LINQ Get列表子集
我有一些产品结构,比如ProductId和ProductVariantId。每种产品都可以有多种变体。 例如,Product1可以有变体1和变体2。Product2可以有变体1、2和3,因此我有以下列表:C# 具有困难条件的C LINQ Get列表子集,c#,linq,list,C#,Linq,List,我有一些产品结构,比如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, P
ProductId: 1, ProductVariantId 1
ProductId: 1, ProductVariantId 2
ProductId: 2, ProductVariantId 1
ProductId: 2, ProductVariantId 2
ProductId: 2, ProductVariantId 3
我想做的是为productId只获取一个给定的变量。当productId没有给定变量时,我的机制应该获得最大值
因此,对于给定的变量3,我的示例应该如下所示:
ProductId: 1, ProductVariantId 2 (maximum)
ProductId: 2, ProductVariantId 3
我试着这样做:
products.ToList().Where(x => x.ProductVariant == givenProductVariant)
我想添加的是某种数据库,它与productId不同,并获得最大值
我可以寻求一些帮助吗?如果ProductVariatid=3,您可以使用此GroupBy方法,按bool或ProductVariatid desc对组进行排序:
您可以使用此GroupBy方法,如果ProductVariatid=3,则按bool对组进行排序,或者改为按ProductVariatid desc对组进行排序:
你能展示你的产品类别的结构吗?你说每个产品可以有很多变体,但似乎每个产品只有一个productid和productvariantid属性。因此,确保我们了解您正在处理的内容会很有帮助。一个更有意义的示例还将包含ProductVariatid=4的产品,如果另一个产品的ProductVariatid=3,则应将其排除在外。您能展示产品类的结构吗?你说每个产品可以有很多变体,但似乎每个产品只有一个productid和productvariantid属性。因此,确保我们了解您正在处理的内容会很有帮助。一个更有意义的示例还将包含ProductVariatid=4的产品,如果有另一个产品的ProductVariatid=3,则应将其排除在外。
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
class Product
{
public int ProductId { get; set; }
public int ProductVariantId { get; set; }
}
static void GetMaxProduct(IList<Product> list,int variant)
{
var query = from l in list
group l by l.ProductId into g
select g.FirstOrDefault(x => x.ProductVariantId == variant) ?? g.OrderBy(x => x.ProductVariantId).Last();
foreach (Product p in query)
{
Console.WriteLine("ProductId:" + p.ProductId + " ProductVariantId:" + p.ProductVariantId);
}
}
static void Main(string[] args)
{
List<Product> list = new List<Product>()
{
new Product{ ProductId=1, ProductVariantId=1},
new Product{ ProductId=1, ProductVariantId=2},
new Product{ ProductId=2, ProductVariantId=1},
new Product{ ProductId=2, ProductVariantId=2},
new Product{ ProductId=2, ProductVariantId=3},
};
GetMaxProduct(list, 3);
GetMaxProduct(list, 4);
GetMaxProduct(list, 1);
}