Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1240
  • Last Modified:

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?
0
ChetOS82
Asked:
ChetOS82
  • 2
  • 2
  • 2
1 Solution
 
Joel CoehoornDirector of Information TechnologyCommented:
No.  You'll have to iterate.
0
 
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?
0
 
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.  
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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.
0
 
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.
0
 
ChetOS82Author Commented:
Thanks
0

Featured Post

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.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now