c# - 在 C# 中生成多个字符串列表中的元素组合

标签 c# .net

我正在尝试自动化嵌套的 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 循环

最佳答案

只需对每个连续的列表进行交叉连接:

 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));
 }

结果:

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 

注意事项:

  • Declaring lstRes as an IEnumerable<string> prevents the unnecessary creation of additional lists that will be thrown away with each iteration

  • The instinctual null is used so that the first cross-join will have something to build on (with strings, null + s = s)

关于c# - 在 C# 中生成多个字符串列表中的元素组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28610091/

相关文章:

c# - 如何查看是否安装了驱动程序?

c# - 处理后的 Reactive Rx 2.0 EventLoopScheduler ObjectDisposedException

.net - 保存图像: A generic error occurred in GDI+. (vb.net)

c# - 如何获取和设置当前运行空间中的变量? (基于 cmdlet 的模块)

c# - 将嵌套键值对分组到字典中

c# - 为什么 ViewComponentResult.ExecuteResult 方法返回 void?

.net - 如何以编程方式清除 MSMQ 系统队列日志?

c# - XML WriteAttributeString 错误

c# - MassTransit - 等待所有事件完成,然后继续处理

c# - 在 .NET/C# 中是否有类似 Ruby 中的 Or-Equals 的东西?