I have two list
List<string> listA;
List<string> listB;
How to get next item of listA when im iterating with listB? Pseudocode:
List<dynamic> listC = new List<dynamic>();
foreach (var elementA in listA)
{
listC.Add(new
{
a: elementA,
b: listB.TakeNextItem() // how to achive this?
});
}
You could use Enumerable.Zip
:
var listC = listA
.Zip(listB, (a, b) => new { a, b })
.ToList();
This iterates over both lists and projects items into a new list.
It also statically types your listC
variable, rather than using dynamic
.
You could use a for loop instead of a foreach loop and then use the current index to access both listA
and listB
at the same time.
List<dynamic> listC = new List<dynamic>();
// When listA Count is as bigger as listB don't execute for-loop
if (listA.Count > listB.Count) {
return;
}
for (int i = 0; i < listA.Count; i++) {
listC.Add(new {
a = listA[i],
b = listB[i]
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.