如何在 IEnumerable < KeyValuePair<string, int>> 中添加新对

How to add new pairs in IEnumerable < KeyValuePair<string, int>>

我正在尝试找到解决此问题的方法 给定一个 IEnumerable<KeyValuePair<string, int>> 我需要向它添加新的键值对

我尝试执行以下操作:

myKeyValue.Add(new IEnumerable<KeyValuePair<string, int>> ...)

但我收到以下错误:

IEnumerable<KeyValuePair<string, int>> does not contain a definition for Add and no accessible extension method Add accepting a first argument of type IEnumerable<KeyValuePair<string, int>> could be found

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-s 的列表,检查一个键是否只能在列表中出现一次

IEnumerable 是 read-only。你不能修改它。您可以投影到 new 集合:

var newDict = oldDict.Append(new KeyValuePair<string, int>(newValue));

但这不会改变原始集合。

如果您需要修改原始集合(如果您仅将其作为IEnunmerable给出,这似乎很危险),您可以尝试 转换为可写接口(如 ICollection<KeyValuePair<...>>)并添加一个项目,但如果转换失败(意味着底层对象实际上不可写),您将无能为力。