Reputation: 897
I have two list objects in c# as mentioned below
List A
[0]
Count="0",
CountType="0",
InvTpeCode="DLX"
[1]
Count="0",
CountType="0"
InvTpeCode="STD"
List B
[0]
Count="2",
CountType="17"
[1]
Count="12",
CountType="14"
I have tried using foreach to update list a value with list b values but unfortunately i am not able to bring the desired output.
Note : Both the list are of same size only
Upvotes: 3
Views: 1605
Reputation: 512
a foreach-loop is unpractible here, i would do the following:
for(int i=0; i < A.Count(); i++)
{
A[i].Count = B[i].Count;
A[i].CountType = B[i].CountType;
}
But keep in mind this will die hard if List A is longer than B.
Upvotes: 1
Reputation: 9365
If the lists are the same size then a for loop will be enough:
for (int i=0; i< A.Count();i++)
{
A[i].Count = B[i].Count;
A[i].CountType = B.CountType;
}
Upvotes: 2
Reputation: 383
First assure that the lists are the same size.
var index = 0;
foreach ( ObjA itemA in listA) {
replaceValues(ObjA, listB[index]);
index++;
}
The method replaceValues should then replace the properties of ObjA with the properties of the item from listB (with the same position). But I think it makes no sense to use an foreach here. A simple for-loop can be used - as you need the index of the current element anyway.
Upvotes: 0
Reputation: 46005
Instead of for
-loop you can also use Zip
var result = A.Zip(B, (a, b) => new Item {
InvTpeCode = a.InvTpeCode,
CountType = b.CountType,
Count = b.Count });
Upvotes: 5