我正在嘗試找到解決此問題的方法 鑒于IEnumerable<KeyValuePair<string, int>>我需要向其添加新的鍵值對
我嘗試執行以下操作:
myKeyValue.Add(new IEnumerable<KeyValuePair<string, int>> ...)
但我收到以下錯誤:
IEnumerable<KeyValuePair<string, int>>不包含定義,也找不到接受型別的第一個引數的可Add訪問擴展方法AddIEnumerable<KeyValuePair<string, int>>
uj5u.com熱心網友回復:
IEnumerable是只讀的。你不能修改它。您可以投影到一個新的集合:
var newDict = oldDict.Append(new KeyValuePair<string, int>(newValue));
但這不會改變原始集合。
如果您需要修改原始集合(如果僅將其作為 給出,這似乎很危險)IEnunmerable,您可以嘗試轉換為可寫介面(如ICollection<KeyValuePair<...>>實際上是可寫的)你無能為力。
uj5u.com熱心網友回復:
IEnumerable<T>真的不包含方法.Add(...)。添加IList<T>介面中宣告的方法;
不過,您可以使用 LINQ 擴展方法.Append(item)
這是一些示例代碼:
IEnumerable<KeyValuePair<string, int>> myKeyValue = new List<KeyValuePair<string, int>>();
myKeyValue = myKeyValue.Append(new IEnumerable<KeyValuePair<string, int>>());
而且,如果可能的話,看看你的問題,你可以試試Dictionary<string, int>這基本上是一個 KeyValuePair 串列,檢查一個鍵只能在串列中出現一次
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482046.html
標籤:C#
