I'm trying to find a solution to this problem
Given a IEnumerable<KeyValuePair<string, int>>
I need to add new key value pair to it
I tried to do the following:
myKeyValue.Add(new IEnumerable<KeyValuePair<string, int>> ...)
But I'm getting the following error:
IEnumerable<KeyValuePair<string, int>>
does not contain a definition forAdd
and no accessible extension methodAdd
accepting a first argument of typeIEnumerable<KeyValuePair<string, int>>
could be found
CodePudding user response:
IEnumerable
is read-only. You can't modify it. You could project to a new collection:
var newDict = oldDict.Append(new KeyValuePair<string, int>(newValue));
but that does not change the original collection.
If you need to modify the original collection (which seems dangerous if you are only given it as an IEnunmerable
), you could try casting to a writable interface (like ICollection<KeyValuePair<...>>
) and add an item, but if that cast fails (meaning the underlying object is not actually writable) there's nothing else you can do.
CodePudding user response:
IEnumerable<T>
really does not contain method .Add(...)
.
Add method declared in IList<T>
interface;
Though, you can use a LINQ extension method .Append(item)
And here is some example code:
IEnumerable<KeyValuePair<string, int>> myKeyValue = new List<KeyValuePair<string, int>>();
myKeyValue = myKeyValue.Append(new IEnumerable<KeyValuePair<string, int>>());
And, if possible, looking at your question, you can try Dictionary<string, int>
which is basically a list of KeyValuePair-s checking that a key could be presented in a list only once