简体   繁体   English

Linq查询更新对象列表,其中包含来自另一个对象列表的一些数据

[英]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. IList<UpdatesObject>包含更新。

Common distinct field in both objects is ID, and UpdatesObject field is just a subset of all DetailsObject fields. 在这两个对象的公共领域的不同是ID,并UpdatesObject场只是所有的子集DetailsObject领域。

Can I use Linq method to update DetailsObject with values from UpdatesObject . 我可以使用LINQ方法来更新DetailsObject与价值观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. 我知道最简单的解决方案是迭代UpdatesObject并在每次迭代中找到ID匹配的对象,然后更新必要的内容。

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: 您可以根据ID列连接两个列表,然后使用foreach循环更新对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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