我正在尝试自动化嵌套的foreach,只要有一个主列表保存字符串列表作为以下场景的项目.
例如,我有5个主列表lstMaster持有的字符串列表
List<string> lst1 = new List<string> { "1", "2" };
List<string> lst2 = new List<string> { "-" };
List<string> lst3 = new List<string> { "Jan", "Feb" };
List<string> lst4 = new List<string> { "-" };
List<string> lst5 = new List<string> { "2014", "2015" };
List<List<string>> lstMaster = new List<List<string>> { lst1, lst2, lst3, lst4, lst5 };
List<string> lstRes = new List<string>();
foreach (var item1 in lst1)
{
foreach (var item2 in lst2)
{
foreach (var item3 in lst3)
{
foreach (var item4 in lst4)
{
foreach (var item5 in lst5)
{
lstRes.Add(item1 + item2 + item3 + item4 + item5);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想自动化下面的for循环,无论主列表lstMaster持有的列表项的数量是多少
只需对每个连续列表进行交叉连接:
IEnumerable<string> lstRes = new List<string> {null};
foreach(var list in lstMaster)
{
// cross join the current result with each member of the next list
lstRes = lstRes.SelectMany(o => list.Select(s => o + s));
}
Run Code Online (Sandbox Code Playgroud)
结果:
List<String> (8 items)
------------------------
1-Jan-2014
1-Jan-2015
1-Feb-2014
1-Feb-2015
2-Jan-2014
2-Jan-2015
2-Feb-2014
2-Feb-2015
Run Code Online (Sandbox Code Playgroud)
笔记:
声明
lstRes为IEnumerable<string>可以防止不必要地创建将在每次迭代时丢弃的其他列表使用本能
null,以便第一个交叉连接将有一些东西可以构建(使用字符串null + s = s)
| 归档时间: |
|
| 查看次数: |
1680 次 |
| 最近记录: |