简体   繁体   中英

Copy a list of objects from one list to another based on id

Basically I have two lists of objects. I need to do something like update first list from second list based on the id property that matches between the lists. How can I achieve this without using foreach loop.

public class Test1
{
    int Id;
    List<Test2> Test2Values;
}

public class Test2
{
    int Test1Id;
    string valueString;
}

public class Main
{
    public void Test()
    {
        List<Test1> testList1 = GetTest1();
        List<Test2> testList2 = GetTest2();

        foreach(Test1 t in testList1)
            t.Test2Values = testList2.Where(tl => tl.Test1Id == t.Id).ToList();
    }
}

That should do the trick. First build a dictionary out of testList2 . Key it by Test1Id . Then select each item from testList1 . Check if it's id is in the dictionary. If so replace the list with new values else keep the old value.

var dict = testList2
            .GroupBy(t2 => t2.Test1Id)
            .ToDictionary(
                gr => gr.Key, 
                gr => gr.ToList());

testList1
    .Select(t1 => 
    { 
        t1.Test2Values = dict.ContainsKey(t1.Id) ? dict[t1.Id] : t1.Test2Values;
        return t1;
    })
    .ToList();

使用下面的代码获取两个列表之间的公共项目,然后处理下一个:

 var result = testList1.Where(p => testList2.Any(p2 => p2.Id == p.Id));

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