2015-01-12 20 views
1

我有一個外部循環迭代在字典中匹配的子字符串數組。在內部循環中,我想迭代字典並刪除其中包含子字符串的條目。如何在不收到「集合被修改的異常」的情況下執行此操作?如何從字典中動態刪除鍵值對,如果鍵包含一些子字符串?

foreach (string outerKey in new string[] { "PAYERADDR_PAYERNAME", "RECADDR_RECNAME", "PAYERADDR_ADDR", "RECADDR_ADDR" }) 
{ 
    foreach (var item in _generalWorksheetData.Where(kvp => kvp.Value.Contains(outerKey)).ToList()) 
     { 
      _generalWorksheetData.Remove(item.Key); 
     } 
} 
+0

顯示您的代碼。 – dario

+0

你正在寫的是你想刪除的項目有一個鍵包含一些字符串,但在你的代碼中,你檢查值'kvp.Value.Contains(outerKey)';-)與你的代碼,你幾乎在那裏。它不起作用,因爲你選擇字典的項目'kvp'('KeyValuPair'),如果它們是循環的一部分,你不能改變它。如果你把鑰匙當作'.Select(kvp => kvp.Key).ToList()'它會起作用; - ] – t3chb0t

回答

6

你需要一個新的集合:

List<string> todelete = dictionary.Keys.Where(k => k.Contains("substring")).ToList(); 
todelete.ForEach(k => dictionary.Remove(k)); 

或用foreach

foreach (string key in todelete) 
    dictionary.Remove(key); // safe to delete since it's a different collection 

如果Dictionary.Keys實施IList代替只是ICollection y ou可以在向後的for循環中訪問它以刪除它們。但既然沒有索引器,你就不能。

+0

好的一個學習新的東西..儘管這..foreach是好的... –

+1

@PranayRana:其實'List.ForEach'不是之所以能夠工作,是因爲我用'ToList'創建了一個新列表。正如你現在所看到的,你也可以使用簡單的'foreach'循環。 –

1

AFAIK,你不能。但是,您可以將這些對存儲在列表中,並在與第一個循環分開的循環中刪除它們。

1

查找匹配並刪除條目下面

var keysWithMatchingValues = dictionary.Where(d => d.Key.Contains("xyz")) 
           .Select(kvp => kvp.Key).ToList(); 

foreach(var key in keysWithMatchingValues) 
    dictionary.Remove(key); 
+0

這不能編譯,因爲'dic'是一個'KeyValuPair',但即使你使用'remove(dic.Key)'這也導致了收集被修改的異常,這是OP想要防止的。如果使用'dictionary.Keys.Where(...)'代替,也會發生同樣的情況。 –

+0

@TimSchmelter - 我發現了問題,並通過列表中的值來解決... –

1

只要更新你的內心foreach如下:

foreach (var item in _generalWorksheetData.Keys.Where(kvp => kvp.Contains(outerKey)).ToList()) 
    { 
     _generalWorksheetData.Remove(item); 
    } 

注意,LINQ擴展方法ToListToArray也允許你修改集合。

 List<string> sampleList = new List<string>(); 
     sampleList.Add("1"); 
     sampleList.Add("2"); 
     sampleList.Add("3"); 
     sampleList.Add("4"); 
     sampleList.Add("5"); 

     // Will not work 
     foreach (string item in sampleList) 
     { 
      sampleList.Remove(item); 
     } 

     // Will work 
     foreach (string item in sampleList.ToList()) 
     { 
      sampleList.Remove(item); 
     } 
相關問題