tags:

views:

126

answers:

2

My requirements:

  • I need to store a collection of objects inside a class,
  • objects must be accessible by their key (which will be unique string), search/remove/replace must work like this

    MyClass somethingNew = new MyClass();
    // set someproperties on somethingNew    
    somethingNew.Id = "FooBar";    
    // theOtherObject already contains an object with the key "FooBar"    
    theOtherObject.Members[somethingNew.Id] = somethingNew;
    
  • when new object is inserted no sort should happen,

  • the property (collection) must be serializable to XML using DataContractSerializer.

So, what to choose for Members property? I guess that List and SortedList are out of the question, so I am about to use generic

Dictionary<string, MyClass>.

Is this the right decision? Does it support serialization?

+2  A: 

Dictionary<string, MyClass> is the correct option in this case.

And yes, it is Serializable.

Justin Niessner
+2  A: 

Another class you may want to consider KeyedCollection<TKey,TItem>. It is also serializable.

The KeyedCollection class is a hybrid between a collection based on the IList generic interface and a collection based on the IDictionary generic interface. Like collections based on the IList generic interface, KeyedCollection is an indexed list of items. Like collections based on the IDictionary generic interface, KeyedCollection has a key associated with each element. *

*Referenced from MSDN documentation from link above.

Edit: One thing to note is that KeyedCollection<TKey,TItem> is an abstract class and you will need to derive an instance of that class, ex) MyClassCollection before you can begin using it.

Wallace Breza
-1 KeyedCollection<TKey, TItem> is an abstract class and can't directly be instantiated. It is also for a specific case when the Key is embedded directly in the Value object (which, in this case, isn't true).
Justin Niessner
Yes, I'm aware that it is an abstract class. But he is doing his lookups based upon `somethingNew.Id` of his `MyClass`. And if this collection is used in many places throughout the application then there is nothing wrong with creating a dedicated collection class `MyClassCollection` to handle access to collections of those objects.
Wallace Breza
@Wallace Breza - You're right. I read the code incorrectly. You might want to update your answer to include the fact that the OP would have to create a custom collection type derived from KeyedCollection<TKey, TItem>.
Justin Niessner
@Justin Niessner - Thanks, I've updated my answer to reflect that.
Wallace Breza
Very nice to point out about this class. Though I won't be using it in this case, it certainly is very useful in many other. Upvoting.
mare