以紧凑的方式迭代两个列表
c#
有没有比以下更紧凑的方法来编写一次迭代两个列表的循环:
var listA = new List<string>();
var listB = new List<int>();
foreach (var (itemFromListA, itemFromListB) in listA.Zip(listB,
(itemFromListA, itemFromListB)=>(itemFromListA, itemFromListB)){
// do something with itemFromListA and itemFromListB
}
键入(itemFromListA, itemFromListB)三遍似乎不必要地繁琐,而且(itemFromListA, itemFromListB)=>(itemFromListA, itemFromListB)对于身份运算符来说,诸如此类的内容太长了。
回答
你可以这样写:
foreach (var (a,b) in listA.Zip(listB, ValueTuple.Create))
网上试试
夏普实验室
- @Ian H It will create a new enumerator object, but valueTuple is a value type, so it will not cause any heap allocation per-item. So the amount of garbage collection needed should be independent of collection size. It will be a bit slower than a regular for-loop, due to the enumerator overhead, but that would not matter in most cases.