I have two Enumberable lists: list1 & list2
I want to take something from list2 and update it in list1 based on a condition
e.g: list1.Id has say for instance 1, 2, 3, 4, 5 etc.
list2.Id has 3, 4
I need to compare these Ids and take the other fields(e.g. name, subject) from list2 which matches list1.Id (3 and 4 in this case) and copy it to list1 other fields(name, subject)
list1:
Id | Name | Subject |
---|---|---|
1 | N1 | S1 |
2 | N2 | S2 |
3 | ||
4 | ||
5 | N5 | S5 |
list2:
Id | Name | Subject |
---|---|---|
3 | N3 | S3 |
4 | N4 | S4 |
Required resultant:
Id | Name | Subject |
---|---|---|
1 | N1 | S1 |
2 | N2 | S2 |
3 | N3 | S3 |
4 | N4 | S4 |
5 | N5 | S5 |
4
Answers
Not quite sure what do you need. I assume you need to update data in enum1 based on enum2, in that case do this:
Lets say you have a class subject as below:
and you have two lists as below:
If you want to merge them, what you do is basically go through all the items in enum2 and check if the item exist in the enum1 then u update it. If not, you can add it to the list. As below:
In this way, enum1 will be the merged list of the two.
How about this?
If you are looking for a solution without a Foreach, have you thought of using Dictionaries for this part, where you set the key as the id of your object and the value as the object itself.
where you add you values like this:
Then you will be able to do a merge without a Foreach like this:
This way, the dictB gets merged in the dictA. Just reverse the values if you want the opposite to happen.