首页 > 解决方案 > 如何连接多个列表值并生成唯一名称

问题描述

我有一个包含 3-4 个项目的列表对象,例如(颜色、大小、单位),每个列表都有另一个列表,例如颜色列表有多个值(红色、绿色、蓝色)。我想生成像 (red-xl-pcs)(red-xxl-pcs)(blue-xl-pcs)(blue-xxl-pcs) 这样的名称

我的模型:

public class Attributes
{
    public int AttributeId { get; set; }
    public string AttributeName { get; set; }

    public IEnumerable<AttributesValue> AttributesValues { get; set; }
}

public class AttributesValue
{
    public int AttributeValueId { get; set; }
    public string AttributeValueName { get; set; }
}

我的控制器:

public async Task<ActionResult> GetProductAttribute(int productId)
    {
        LoadSession();
        var productAttributes = await _objProductDal.GetProductAttribute(productId, _strWareHouseId, _strShopId);


        foreach (var attribute in productAttributes)
        { 
            attribute.AttributesValues = await _objProductDal.GetProductAttributeValue(productId, attribute.AttributeId, _strWareHouseId, _strShopId);
        }

        return PartialView("_AttributeTablePartial", productAttributes);
    }

我的输出是这样的: 在此处输入图像描述

现在我想要另一个与所有值名称连接的名称列表,例如:

(12/y - 棉花 - 绿色), (12/y - 棉花 - 黄色) .... 它将生成 8 个独特的产品名称。

我怎样才能做到这一点?

标签: c#asp.net-mvc

解决方案


这就是你所追求的吗?遍历每个列表并结合所有可能性?

var first = new List<string> { "one", "two" };
var second = new List<string> { "middle" };
var third = new List<string> { "a", "b", "c", "d" };
var all = new List<List<string>> { first, second, third };

List<string> GetIds(List<List<string>> remaining)
{
    if (remaining.Count() == 1) return remaining.First();
    else
    {
        var current = remaining.First();
        List<string> outputs = new List<string>();
        List<string> ids = GetIds(remaining.Skip(1).ToList());

        foreach (var cur in current)
            foreach (var id in ids)
                outputs.Add(cur + " - " + id);

        return outputs;
    }
}

var names = GetIds(all);

foreach (var name in names)
{
    Console.WriteLine(name);
}

Console.Read();

结果如下:

one - middle - a
one - middle - b
one - middle - c
one - middle - d
two - middle - a
two - middle - b
two - middle - c
two - middle - d

复制并稍微改编自Generate all Combinations from Multiple (n) Lists


推荐阅读