I have two List<T>
objects:
For example:
List 1:
ID, Value where Id is populated and value is blank and it contains say IDs from 1 to 10.
1,""
2,""
...
10,""
List 2:
ID, Value and other attributes all filled with values but this list is a subset of List 1 in terms of IDs. (e.g only 3 items)
2,67
4,90
5,98
What I want is a merged list 1, but with updated values. Does anyone have any good extension method which will do this or any elegent code to perform this operation. The final list should be:
ID, Value
1,""
2,67 //value from list 2
3,""
4,90
5,98
6,""
...
10,""
If you have both lists sorted by ID, you can use a variation of the classical merge algorithm:
Note that this also requires
list2
to be a strict subset oflist1
in terms of ID (i.e.list1
really contains all ids oflist2
)Of course you can also wrap this in an extension method
This is O(m*n) but should do the job for arbitrary lists
If the lists are guaranteed ordered, then it could be brought down to O(n) at the cost of more code. The algortihm would be
use linq: list1=list2.Union(list1);
I would probably use a dictionary rather than a list:
If you are talking about properties of an object, it will be trickier, but still doable.