2013-12-12 90 views
2

我想從字典中刪除所有具有空值的元素。我已經試過如下:如何從Dictionary <string,string>中刪除空元素?

MyDict = MyDict.Where(item => !string.IsNullOrEmpty(item.Value)); 

但是,這引發異常:

Unable to cast object of type 'WhereEnumerableIterator' 1 
[System.CollectionsGeneric.KeyVauePair' 2[System.String,System.String]]' to type 
'System.Collections.Generic.Dictionary' 2[System.String,System.String]'. 

有一些其他的方式來做到這一點?

回答

3

問題出在分配而不是Where調用中。

MyDict = MyDict.Where(item => !string.IsNullOrEmpty(item.Value)) 
       .ToDictionary(i => i.Key); 
+0

錯誤:方法'ToDictionary'沒有重載需要0個參數。 – 4thSpace

+0

@ 4thSpace - 你去了。 – Hogan

+0

謝謝!現在我得到一個如下所示的錯誤:不能隱式地將類型'System.Collections.Generic.Dictionary <字符串,System.Collections.Generic.KeyValuePair <字符串,字符串>>'轉換爲'System.Collections.Generic.Dictionary <字符串,字符串>」。你對此有任何想法。字典被定義爲MyDict 。 – 4thSpace

0

Where()返回IEnumerable。您需要在IEnumerable上撥打.ToDictionary(),然後將其過濾得到Dictionary

相關問題