如何在C#中根据属性筛选匹配的产品变体?
筛选匹配所有指定属性的产品变体
我有多个产品变体,每个变体带有动态创建的属性,已定义SingleVariety和SingleAttribute实体类,同时提供了示例变体数据与筛选属性集合。需要找出匹配所有筛选属性的产品变体(比如ID为1的变体),尝试过Predicate和LINQ但未成功,求解决方法。
实体类定义
public class SingleVariety { [JsonProperty("varietyId")] public int VarietyId { get; set; } [JsonProperty("varietyName")] public string VarietyName { get; set; } [JsonProperty("sku")] public string Sku { get; set; } public List<SingleAttribute> Attributes { get; set; }= new List<SingleAttribute>(); } public class SingleAttribute { [JsonProperty("attributeName")] public string AttributeName { get; set; } [JsonProperty("attributeValue")] public string AttributeValue { get; set; } [JsonProperty("varietyId")] public int VarietyId { get; set; } }
示例变体数据
var varities = new List<SingleVariety>() { new SingleVariety { Sku="testsku", VarietyId=1, VarietyName="test 1", Attributes = new List<SingleAttribute> { new SingleAttribute { AttributeName = "Size", AttributeValue="Large" }, new SingleAttribute{ AttributeName = "Color", AttributeValue = "Red"} } }, new SingleVariety { Sku="testsku2", VarietyId=2, VarietyName="test 2", Attributes = new List<SingleAttribute> { new SingleAttribute { AttributeName = "Size", AttributeValue="Small" }, new SingleAttribute{ AttributeName = "Color", AttributeValue = "Red"} } }, new SingleVariety { Sku="testsku3", VarietyId=3, VarietyName="test 3", Attributes = new List<SingleAttribute> { new SingleAttribute { AttributeName = "Size", AttributeValue="Very Large" }, new SingleAttribute{ AttributeName = "Color", AttributeValue = "Black"} } } };
筛选属性集合
var filterObject = new List<SingleAttribute> { new SingleAttribute { AttributeName = "Size", AttributeValue="Large" }, new SingleAttribute{ AttributeName = "Color", AttributeValue = "Red"} };
解决方案
要筛选出匹配所有筛选属性的变体,核心逻辑是:每个变体必须包含筛选集合中的所有属性(属性名和属性值完全匹配)。以下是两种可行的LINQ实现方式:
方式一:使用字典优化匹配效率
// 将筛选属性转换为字典(属性名作为键,属性值作为值),提升匹配速度 var filterDict = filterObject.ToDictionary(attr => attr.AttributeName, attr => attr.AttributeValue); // 筛选出满足所有筛选条件的变体 var matchedVarieties = varities.Where(variety => filterDict.All(filterItem => variety.Attributes.Any(attr => attr.AttributeName == filterItem.Key && attr.AttributeValue == filterItem.Value) )).ToList();
方式二:直接遍历筛选集合
如果筛选集合规模较小,也可以直接使用双层All/Any判断:
var matchedVarieties = varities.Where(variety => filterObject.All(filterAttr => variety.Attributes.Any(varietyAttr => varietyAttr.AttributeName == filterAttr.AttributeName && varietyAttr.AttributeValue == filterAttr.AttributeValue) )).ToList();
逻辑说明
filterObject.All(...):确保筛选集合中的每一个属性都必须被匹配variety.Attributes.Any(...):检查当前变体的属性列表中是否存在与筛选属性完全匹配的项- 只有当所有筛选属性都在变体的属性中找到对应匹配时,该变体才会被选中
内容的提问来源于stack exchange,提问作者Daisy
相关产品推荐
相关产品推荐

