Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading