Converting ICollection<> to KeyedCollection<>

I have a generic ICollection (lets say List<object>).  I want to create a System.Collections.ObjectModel.KeyedCollection<string, object> from it.

How can I "convert" the ICollection to a KeyedCollection without iterating though each element?  Can I set the underlying collection in the KeyedCollection to my ICollection?
LVL 18
Who is Participating?

Improve company productivity with a Business Account.Sign Up

Joel CoehoornConnect With a Mentor Director of Information TechnologyCommented:
No.  You'll have to iterate.
Jaime OlivaresSoftware ArchitectCommented:
it is not possible without iterating, even more when you have to specify the key for each element.
Who will "guess" the key for each element?
Joel CoehoornDirector of Information TechnologyCommented:
@jaime: you have to inherit your own class from keyedcollection, and part of that is overriding an abstract method that will extract the key from the item.  
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Jaime OlivaresSoftware ArchitectCommented:
yeah, I know, I am trying to state that there is not a ready-made solution for this, for the reason explained.
ChetOS82Author Commented:
As jcoehoorn said, there is no reason to specify the key, as it is determined from the value.

Anyway, after more research I agree with jcoehoorn.  The only way to add a value to a KeyedCollection is though the Add or SetItem methods.

I think the reason for this is because, internally, KeyedCollection is both an IList and an IDictionary and it can switch after a certain number of values have been added.  Even if there were a ICollection parameter in the constructor, it would still be iterating the collection.
ChetOS82Author Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.