需要一个递归函数来解决典型的电子商务多变量问题
本文关键字:典型的 解决 电子商务 问题 变量 递归函数 一个 | 更新日期: 2023-09-27 18:01:35
假设我有以下数据(为了可读性,使用伪代码):
var myVariations = [
{ Name = "Color", Values = ["Red", "Yellow", "Green" /*, etc. */] },
{ Name = "Size", Values = ["S", "M", "L" /*, etc. */] },
{ Name = "Length", Values = ["34", "35", "36" /*, etc. */] },
/* and so on...(up to 5 total) */
];
我可以像这样用LINQ获取这些数据:
var myVariations = myProduct.Variations.ToList();
我如何将这些变化映射到这样的结构中(对于eBay Trading API):
var ebayVariations = [
{
Name = "Red-S-34",
Value = [
// yes, these are arrays with only one item
{ Name = "Color", Values = [{Value = "Red"}] },
{ Name = "Size", Values = [{Value = "S"}] },
{ Name = "Length", Values = [{Value = "34" }] }
]
},
/* etc for all possible combinations */
];
显然,Values
数组只保存一个值的事实有点奇怪;但在eBay的交易API中,如果我在一个变量中列出多个值(与这种递归的东西相比,这很容易做到),它会抱怨。因此,如果您熟悉eBay交易API,我如何才能以"最佳"方式使其工作,与eBay打算列出的变化方式一致(通过AddFixedPricedItem调用,如果您关心)。
我对eBay Trading API不了解,但是这里有一篇关于用LINQ计算笛卡尔积的文章(最后一步放弃递归,转而使用聚合)。
我稍微改变了术语,但写了澄清注释。
public IEnumerable<Combination> GetCombinations(Variation[] variations, int variationIndex, IEnumerable<VariationPosition> aggregatedPositions)
{
// We should choose one position from every variation,
// so we couldn't produce combination till we reach end of array.
if (variationIndex < variations.Length)
{
// Pick current variation.
var currentVariation = variations[variationIndex];
// Every variation has list of possible positions (Color could be Green, Redm, Blue, etc.).
// So we should walk through all the positions
foreach (var val in currentVariation.Positions)
{
// Current position. Variation's name will be used during creating result Combination.
var position = new VariationPosition()
{
Name = currentVariation.Name,
Value = val
};
// Add position to already aggregated on upper levels of recursion positions.
var newPositions = aggregatedPositions.Concat(Enumerable.Repeat(position, 1));
// So we picked some variation position
// Let's go deeper.
var combinations = this.GetCombinations(variations, variationIndex + 1, newPositions );
// This piece of code allows us return combinations in iterator fashion.
foreach (var combination in combinations)
{
yield return combination;
}
}
}
else
{
// We reached end of variations array
// I mean we have one position of every variation.
// We concatenate name of positions in order to create string like "Red-S-34"
var name = aggregatedPositions.Aggregate("", (res, v) => res += v.Name);
// This code is a little bit naive, I'm too lazy to create proper infrastructure,
// But its mission is to create content for property Value of your ebayVariations item.
var value = aggregatedPositions
.Select(v => new { Name = v.Name, Values = new[] { new { Value = v.Value } } })
.ToArray();
// And we return completed combination.
yield return new Combination()
{
Name = name,
Value = value,
};
}
}
和用法:
var allCombinations = this.GetCombinations(inputVariations, 0, new VariationPosition[0]).ToArray();