2016-08-11 58 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 - 這是否幫助你解決問題? –