'Updating fields in one list from another list [closed]
Is there a better or more efficient way to do this?
Both of these objects have the same Id and some similar fields that I want to update.
foreach (var i in oldItems)
{
foreach (var j in newItemValues)
{
if(i.id == j.Id)
{
j.field1 = (decimal)i.field1;
j.field2 = (decimal)i.field2;
}
}
}
Solution 1:[1]
try this maybe you are like this;
foreach (var n in newItemValues)
{
Item item = oldItems.FirstOrDefault(x => x.Id == n.Id);
if (item != null)
{
n.field1 = item.field1;
n.field2 = item.field2;
}
}
Edit: If you keep oldItems
in a HashSet or HashTable by keeping key as Id the time taken will slow to O(N).
Solution 2:[2]
Convert oldItems
or newItemValues
into a Map before looping.
That will reduce computational complexity from O(n^2) to O(n)
Solution 3:[3]
You can do this by Linq Query
newItemsValues =
(from t1 in oldItems
join t2 in newItemsValues on t1.Id equals t2.Id
select new YourModel { field1 = t1.field1 ,field2 = t1.field2 }
).ToList();
result will a list of all matching items where oldItems Id
will be equals to newItemsValues Id
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sergey Alaev |
Solution 3 |