这很普遍-尤其是当您尝试使代码变得更加数据驱动时-需要遍历关联的集合。例如,我刚刚完成了一段代码,如下所示:
string[] entTypes = {"DOC", "CON", "BAL"};
string[] dateFields = {"DocDate", "ConUserDate", "BalDate"};
Debug.Assert(entTypes.Length == dateFields.Length);
for (int i=0; i<entTypes.Length; i++)
{
string entType = entTypes[i];
string dateField = dateFields[i];
// do stuff with the associated entType and dateField
}
Run Code Online (Sandbox Code Playgroud)
在Python中,我将编写类似以下内容的内容:
items = [("DOC", "DocDate"), ("CON", "ConUserDate"), ("BAL", "BalDate")]
for (entType, dateField) in items:
# do stuff with the associated entType and dateField
Run Code Online (Sandbox Code Playgroud)
我不需要声明并行数组,不需要断言我的数组长度相同,也不需要使用索引来取出项目。
我感觉有一种使用LINQ在C#中执行此操作的方法,但我不知道它可能是什么。是否有一些简单的方法可以遍历多个关联的集合?
编辑:
我认为,这要好一些-至少在我可以在声明时手动压缩集合并且所有集合都包含相同类型的对象的情况下:
List<string[]> items = new List<string[]>
{
new [] {"DOC", "DocDate"},
new [] {"CON", "ConUserDate"},
new [] {"SCH", "SchDate"}
};
foreach (string[] item in items)
{
Debug.Assert(item.Length == 2);
string entType = item[0];
string dateField = item[1];
// do stuff with the associated entType and dateField
}
Run Code Online (Sandbox Code Playgroud)
在 .NET 4.0 中,他们向 IEnumerable 添加了“Zip”扩展方法,因此您的代码可能类似于:
foreach (var item in entTypes.Zip(dateFields,
(entType, dateField) => new { entType, dateField }))
{
// do stuff with item.entType and item.dateField
}
Run Code Online (Sandbox Code Playgroud)
现在我认为最简单的方法就是将其保留为 for 循环。有一些技巧可以让您引用“其他”数组(例如,通过使用提供索引的 Select() 重载),但它们都不像简单的 for 迭代器那样干净。
这是一篇关于 Zip 的博客文章以及您自己实现它的方法。同时应该让你继续前进。
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |