Merge and Update Two Lists in C#
Solution 1
I would probably use a dictionary rather than a list:
// sample data
var original = new Dictionary<int, int?>();
for (int i = 1; i <= 10; i++)
{
original.Add(i, null);
}
var updated = new Dictionary<int, int>();
updated.Add(2, 67);
updated.Add(4, 90);
updated.Add(5, 98);
updated.Add(11, 20); // add
// merge
foreach (var pair in updated)
{
original[pair.Key] = pair.Value;
}
// show results
foreach (var pair in original.OrderBy(x => x.Key))
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
If you are talking about properties of an object, it will be trickier, but still doable.
Solution 2
use linq: list1=list2.Union(list1);
Solution 3
This is O(m*n) but should do the job for arbitrary lists
foreach (var record in List1)
{
var other = List2.FirstOrDefault(x => x.Key == record.Key);
if(other != null) record.Value = other.Value;
}
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
Current items start as head of each list
While items remain in both lists
If the current item of list1 has lower key than list2 advance to next in list1
else if the current item of list2 has lower key than list1 advance to next in list2
else copy value from current list2 item into list1 item and advance both lists.
chugh97
Updated on November 07, 2020Comments
-
chugh97 over 3 years
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,98What 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,"" -
BuddhiP over 11 yearsPlease provide some explanation here. Remove unnecessary commented code.
-
surfmuggle over 10 yearsI tried your code with two lists of type
list<Student>
the class student looks like thisStudent student = new Student(){Id=1, Name="foo"}
Using this syntaxlist1 = list2.ToList().Union(list1.ToList()).ToList();
but it did not merge the two lists; it just glued them together like a UNION -see example 3. Are you sure itmerges the list with updated values
? -
surfmuggle over 10 yearsI found this question on how to remove duplicates while merging lists and it confirms that your code works only if the class overrrides
GetHashCode()
andEquals()