Reputation: 391
I have list of two objects:
IList<DetailsObject>
and
IList<UpdatesObject>
containing updates.
Common distinct field in both objects is ID, and UpdatesObject
field is just a subset of all DetailsObject
fields.
Can I use Linq method to update DetailsObject
with values from UpdatesObject
. I know the easiest solution would be to iterate over UpdatesObject
and in each iteration find object where IDs match, and then update what is necessary.
foreach(UpdatesObject uobj in IList<UpdatesObject>)
{
foreach(DetailsObject dobj in IList<DetailsObject>)
{
if (uobj.ID == dobj.ID)
{
dobj.Detail1 = uobj.Detail1;
dobj.Detail2 = uobj.Detail2;
}
}
}
Is it possible to achieve it without such a nested loop?
Upvotes: 1
Views: 683
Reputation: 101742
You can join two lists based on ID column then use a foreach loop to update your objects:
var objects = from u in UpdatesObject
join d in DetailsObject on u.ID equals d.ID
select new { Update = u, Detail = d };
foreach(var obj in objects)
{
obj.Detail.Detail1 = obj.Update.Detail1;
obj.Detail.Detail2 = obj.Update.Detail2;
}
Upvotes: 3