从List <List <string >>获取所有组合

时间:2019-07-11 18:04:40

标签: c#

我想从字符串列表列表中获取所有字符串组合, 我的清单是这样的:

var lstMaster = new List<List<string>>
{
    new List<string>
    {
        "Abc"
    },
    new List<string>
    {
        "B"
    },
    new List<string>
    {
        "C", "D"
    },
    new List<string>
    {
        "E", "F"
    }
};

可能的组合应该是:

Abc,B,C,E .... Abc,B,C,F .... Abc,B,D,E .... Abc,B,D,F

它应该支持其他字符串列表,而不是像这样的示例列表中的4个列表...

我尝试了以下代码,但是它返回重复的组合,而不是所有的可能性:

private static string[] Combinations_From_Lists(List<List<string>> lstMaster)
{
    var totalCombinations = 1;
    foreach (var l in lstMaster)
    {
        totalCombinations *= l.Count == 0 ? 1 : l.Count;
    }

    var res = new string[totalCombinations];
    for (int i = 0; i < lstMaster.Count; ++i)
    {
        var numOfEntries = totalCombinations / lstMaster[i].Count;
        for (int j = 0; j < lstMaster[i].Count; ++j)
        {
            for (int k = numOfEntries * j; k < numOfEntries * (j + 1); ++k)
            {
                if (res[k] == null)
                {
                    res[k] = lstMaster[i][j];
                }
                else
                {
                    res[k] += "|" + lstMaster[i][j];
                }
            }
        }
    }
    return res.ToArray();
}

0 个答案:

没有答案