如何生成C#中属性值列表的笛卡尔积?
生成属性选项的笛卡尔积方案
基于你给出的C#类结构,以下两种方法可以生成所有属性选项的笛卡尔积,并输出你需要的连字符分隔格式。
类结构回顾
public class AttributeOption { public Guid Id { get; set; } public string Name { get; set; } } public class MyAttribute { public Guid Id { get; set; } public string Name { get; set; } public List<AttributeOption> Options { get; set; } = new List<AttributeOption>(); }
方法一:递归实现
递归逻辑直观,逐步组合每个属性的选项与剩余属性的笛卡尔积结果:
public static List<string> GenerateCartesianProduct(List<MyAttribute> attributes) { if (attributes == null || attributes.Count == 0) return new List<string>(); var firstAttrOptions = attributes[0].Options.Select(o => o.Name).ToList(); var remainingProducts = GenerateCartesianProduct(attributes.Skip(1).ToList()); if (!remainingProducts.Any()) return firstAttrOptions; var result = new List<string>(); foreach (var option in firstAttrOptions) { foreach (var product in remainingProducts) { result.Add($"{option}-{product}"); } } return result; }
方法二:LINQ简洁实现
利用Aggregate和SelectMany实现累积式的笛卡尔积计算,代码更紧凑:
public static List<string> GenerateCartesianProductWithLinq(List<MyAttribute> attributes) { var optionLists = attributes.Select(a => a.Options.Select(o => o.Name).ToList()).ToList(); return optionLists.Aggregate( new List<string> { "" }, (current, next) => current.SelectMany(c => next.Select(n => string.IsNullOrEmpty(c) ? n : $"{c}-{n}")).ToList() ); }
使用示例
构建测试数据并输出结果:
var attributes = new List<MyAttribute> { new MyAttribute { Name = "颜色", Options = new List<AttributeOption> { new AttributeOption { Name = "Red" }, new AttributeOption { Name = "White" }, new AttributeOption { Name = "Blue" } } }, new MyAttribute { Name = "尺寸", Options = new List<AttributeOption> { new AttributeOption { Name = "Small" }, new AttributeOption { Name = "Medium" }, new AttributeOption { Name = "Large" } } }, new MyAttribute { Name = "性别", Options = new List<AttributeOption> { new AttributeOption { Name = "Male" }, new AttributeOption { Name = "Female" } } } }; // 任选一种方法生成结果 var products = GenerateCartesianProduct(attributes); // 输出格式符合要求的字符串 foreach (var product in products) { Console.WriteLine(product); }
运行后会输出你需要的格式:
Red-Small-Male Red-Small-Female Red-Medium-Male Red-Medium-Female Red-Large-Male Red-Large-Female White-Small-Male ...
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

