Question

I have string of items as - string item = "a,b,c+1,2,3,4+z,x";

I split this string with + and add to N number of lists as List keysList = item.Split('+').ToList()

From this lists I expect to create keys as

a1z

a1x

a2z

a2x

a3z

a3x etc:-

I have tried below block of code . but something is not correct here

private string GetValue(List<string> keysList, int i, int keyCount, string mainKey)
{
    List<string> tempList = keysList[i].Split(',').ToList();
    foreach (string key in tempList)
    {
        mainKey += key;
        i++;
        if (i == keyCount)
        {
            return mainKey;

        }
        GetValue(keysList, i, keyCount, mainKey);
    }
    return mainKey;
}
Was it helpful?

Solution

Here's one way to do it...

string item = "a,b,c+1,2,3,4+z,x";

var lists = item.Split('+').Select(i => i.Split(',')).ToList();    
IEnumerable<string> keys = null;

foreach (var list in lists) 
{
    keys = (keys == null) ? 
        list : 
        keys.SelectMany(k => list.Select(l => k + l));
}

Fiddle

OTHER TIPS

You can create helper function as follows:

static IEnumerable<string> EnumerateKeys(string[][] parts)
{
    return EnumerateKeys(parts, string.Empty, 0);
}

static IEnumerable<string> EnumerateKeys(string[][] parts, string parent, int index)
{
    if (index == parts.Length - 1)
        for (int col = 0; col < parts[index].Length; col++)
            yield return parent + parts[index][col];
    else
        for (int col = 0; col < parts[index].Length; col++)
            foreach (string key in EnumerateKeys(parts, parent + parts[index][col], index + 1))
                yield return key;
}

Usage demo:

string[][] parts = {
                       new[] { "a", "b", "c" },
                       new[] { "1", "2", "3", "4" },
                       new[] { "z", "x" }
                   };
foreach (string key in EnumerateKeys(parts))
    Console.WriteLine(key);

Online demo: http://rextester.com/HZR27388

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top