linq c# -从另一个列表更新对象列表

kpbwa7wx  于 2022-12-20  发布在  C#
关注(0)|答案(2)|浏览(205)

我有一张物品清单。

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

还有另一份名单。

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

如果主键和外键匹配,我想用第二个列表details的内容更新第一个列表的details属性。

okxuctiv

okxuctiv1#

您可以使用字典来完成此操作。
创建字典以避免重复匹配员工:

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

然后,您可以仅通过字典键来匹配员工。

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 !!!
    }
}
q9rjltbz

q9rjltbz2#

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

相关问题