我有- string item = "a,b,c+1,2,3,4+z,x";
我用+拆分了这个字符串,并将列表keysList = item.Split('+').ToList()添加到N个列表中
在这个列表中,我希望创建密钥
a1z a1x a2z a2x a3z a3x等:-
我试过了下面的代码块。但这里有些地方不对劲
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;
}发布于 2014-05-14 06:34:05
有一种方法..。
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));
}发布于 2014-05-14 06:19:17
您可以如下所示创建助手函数:
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;
}使用演示:
string[][] parts = {
new[] { "a", "b", "c" },
new[] { "1", "2", "3", "4" },
new[] { "z", "x" }
};
foreach (string key in EnumerateKeys(parts))
Console.WriteLine(key);在线演示:http://rextester.com/HZR27388
https://stackoverflow.com/questions/23646863
复制相似问题