2016-08-11 30 views
0

我有一个包含5个成员的课程。 那样:使用LINQ在课堂上更新成员

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值的字典列表。 (一个为第四个,第二个为第五个)

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

我希望我的问题已经够清楚了。

+1

为什么你坚持使用LINQ,当缩写代表的查询*语言* ... –

回答

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

美丽而优雅的方式!非常感谢你! –

+0

我不明白谁给你-1。 –

+0

也从我这里得到upvote :) –

1

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

你应该考虑使用'.TryGetValue'而不是'.ContainsKey'和'[]'。它在这种情况下可能不相关,但在多线程场景中,您的方法将失败,例如并发字典(其中'.TryGetValue'作为* atomic *操作实现) –

+0

同意你说的 - 有价值的评论。只是想让它更接近问题编写的方式 –

+0

@prog_prog - 这是否帮助你解决问题? –