简体   繁体   中英

Linq query for updating list of objects with some data from another list of objects

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM