使用 LINQ 更新 class 中的成员

Update member in class using LINQ

我有一个 class 有 5 个成员。 像那样:

class Demo
{
    public int id;
    public string name;
    public string color;
    public int 4th_member;
    public int 5th_member;
}

我有这个 class 的列表。

对于 4th_member5th_member,我有 2 个包含 int 键和 int 值的字典列表。 (一个代表第 4 个,第二个代表第 5 个)

我想根据字典更新这些成员。 例如,如果字典的键 = id,则将 4th_member 更新为字典的值。

希望我的问题够清楚了。

linq 不用于更新数据,而是用于查询。这是一个可能的解决方案:

foreach(var demo in demoList)
{
    if(dictionaries[0].ContainsKey(demo.id))
    {
        demo.member4 = dictionaries[0][demo.id];
    }

    if (dictionaries[1].ContainsKey(demo.id))
    {
        demo.member5 = dictionaries[1][demo.id];
    }
}

或与 TryGetValue

foreach(var demo in demoList)
{
    int value;
    if(dictionaries[0].TryGetValue(demo.id, out value))
    {
        demo.member4 = value;
    }

    if (dictionaries[1].TryGetValue(demo.id, out value))
    {
        demo.member5 = value;
    }
}

我测试了下面的代码,它工作正常。

如果我正确理解了你的问题,希望这能解决你的问题

var demo = demoTest.Select(s =>
           {
            s.Fourthth_member = dic.GetValueFromDictonary(s.Fourthth_member);
            s.Fifthth_member = dic1.GetValueFromDictonary(s.Fifthth_member);
            return s;
          }).ToList();

//Extension method
public static class extMethod
{
  public static int GetValueFromDictonary(this Dictionary<int, int> dic, int key)
    {
        int value = 0;

        dic.TryGetValue(key, out value);

        return value;
    }
}