Search code examples
c#linq

c# - update list of objects from another list


I have a list of object.

"result": [
    {
        "primaryKey": "123",
        "count": 0,
        "details": [
            {
                "employeeName": "Chris",
            }
        ],
    },
    {
        "primaryKey": "456",
        "count": 10,
        "details": [
            {
                "employeeName": "Nick",
            }
        ],
    },
]

And another list.

"result": [
    {
        "foreignKey": "123",
        "details": [
            {
                "employeeName": "Sean",
            }
        ],
    },
    {
        "foreignKey": "789",
        "details": [
            {
                "employeeName": "Andrew",
            }
        ],
    },
]

I want to update the details property of the first list with the contents of second list details, if the primary key and foreign key matches.


Solution

  • foreach(obj item in result1)
    {
        if(result2.where(x => foreignKey == item.primaryKey).Any())
        {
           string EmpName = result2.where(x => foreignKey == item.primaryKey).FirstOrDefault().employeeName;
           item.employeeName = EmpName ;
        }
    }