【问题标题】:Update member in class using LINQ使用 LINQ 更新类中的成员
【发布时间】:2016-08-11 07:38:44
【问题描述】:

我有一个有 5 名成员的班级。 像这样:

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

我有这个班级的名单。

对于4th_member5th_member,我有2 个带有int 键和int 值的字典列表。 (第 4 次第 1 次,第 5 次第 2 次)

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

我希望我的问题足够清楚。

【问题讨论】:

  • 当首字母缩写代表查询语言 ...时,为什么还要坚持使用linq

标签: c# linq updates


【解决方案1】:

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

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

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

【讨论】:

  • 美丽优雅的方式!非常感谢!
  • 我不明白谁给你-1。
  • @Sathish - 如您所知,在第一个 linq 选项中,您在按键访问字典时失去了 o(1),因此您的第二种方式更好
【解决方案2】:

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

【讨论】:

  • 您应该考虑使用.TryGetValue,而不是使用.ContainsKey[]。在这种情况下它可能不相关,但在多线程场景中,您的方法将失败,例如并发字典(其中.TryGetValue 被实现为 atomic 操作)
  • 同意你所说的——有价值的评论。只是想让它更接近问题的编写方式
  • @prog_prog - 这对您的问题有帮助吗?
  • 感谢您采纳我的建议,但您可以重复使用 value 而不是使用 [] 进行另一个读取访问 :)
  • 我对您的解决方案稍作改动,但它的工作原理。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
相关资源
最近更新 更多