c# - update list of objects from another list

Viewed 42

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.

2 Answers

You can do this using dictionary.

Create dictionary to avoid redundant iterations when matching employees:

var foreignDataDictionary = result2.ToDictionary(item => item.foreignKey);

Then you can match employees just by dictionary key.

foreach (var primary in result1)
{
    // if foreignDataDictionary contains employee key from result1
    // then update employee details
    // otherwise just ignore
    if (foreignDataDictionary.TryGetValue(primary.primaryKey, out var foreign))
    {
        primary.details = foreign.details; // shallow copy !!!
    }
}
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 ;
    }
}
Related