【发布时间】:2015-02-19 15:23:12
【问题描述】:
我正在尝试自动化嵌套的 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);
}
}
}
}
}
无论主列表 lstMaster 持有多少列表项,我都想自动执行以下 for 循环
【问题讨论】:
-
如何将 List
- > 声明为外部父集合?
-
你可以用两个内部 foreaches 解决它。
-
@user30... OP 已经有了这个
-
@user3021830 lstMaster 按照你的建议做
-
非常相关的question。您需要使用的代码是
var result = CartesianProduct(new List<List<string>>() { lst1, lst2, lst3, lst4, lst5 }) .Select(row => String.Join("", row)) .ToList();