2017-02-12 56 views
0

我有一本字典是這樣的:添加新值與列表字典作爲其價值

Dictionary<string,List<string>> StudentsByTeacherName = new Dictionary<string,List<string>>(); 

這本字典是一個循環,我想對於一個特定的密鑰字典價值每個循環得到更新中。如果沒有新的密鑰那裏添加到字典中

foreach (var item5 in StudentsByTeacherName) 
       { 
        if (StudentsByTeacherName.ContainsKey(item5.Key)) 
        { 

        } 
        else 
        { 
         StudentsByTeacherName.Add(item4.Value,StudentName); 
        } 

       } 
+0

列表 abc = StudentsByTeacherName [「item3.Key」]; abc.Add(「def」); – jdweng

+1

你確定你必須自己建立嗎?你最好使用lookup:'var lookup = students.ToLookup(s => s.TeacherName);' –

+0

你的檢查沒有意義。 StudentsByTeacherName將始終包含item5.Key中的鍵,因爲item5是來自StudentsByTeacherName – Brody

回答

2

我想爲一個特定的密鑰字典值中的每個 循環得到更新。如果沒有新的密鑰也添加到字典

對於不是檢查ContainsKey簡單地做:

TeacherName[item3.Key] = yourStringList; 

的索引[]將更新現有密鑰和插入如果該鍵沒有按」 t存在。

+0

的鍵/值對,感謝您的答案。但我不希望現有密鑰更新。我想更新他們的值 –

+0

@HossainEhsani,你真的試過這個代碼嗎? – user3598756

+0

由Habib提供的代碼將更新*值*或添加一個包含該值的新密鑰,即它就像一個「AddOrUpdate」方法。這不是你想要的嗎? – mm8

1

您不能更改您的財產或索引值,因爲這是隻讀的。你可以做的是通過其索引訪問:

foreach (var item5 in StudentsByTeacherName) 
    { 
     if (StudentsByTeacherName.ContainsKey(item5.Key)) 
     { 
      //This will add new values on your list of string on specific 
      //keys and will not delete the existing ones: 

      List<string> list = StudentsByTeacherName[item5.Key]; 
      list.Add("Your additional value here"); 
     } 
     else 
     { 
      StudentsByTeacherName.Add(item4.Value,StudentName); 
     } 
    } 

這將更新字符串列表的價值,而不是密鑰本身。

+0

我認爲這會刪除以前的數據並用新的替換它們。我想把新數據添加到列表中。沒有製作一個全新的列表 –

+0

好吧,我明白了,請看我更新的代碼@HossainEhsani –

0

試試這個。

foreach (var item5 in StudentsByTeacherName) 
{ 
    if(item5.Value == null) 
    { 
     item5.Value = new List<String(); 
    } 

    item5.Value[item4.Key] = item4.Value; 
} 

我假設item4是學生。這將取代現有值或添加新值。