It seems to me that a dictionary is enough for what do you need?
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
var dicionario = new Dictionary<string, MyObject> {
["item1"] = new MyObject("item1", "valor1", 1, 1.1),
["item2"] = new MyObject("item2", "valor2", 2, 2.2),
["item3"] = new MyObject("item3", "valor3", 3, 3.3)
};
Console.WriteLine(dicionario["item2"].Value);
}
}
public class MyObject {
public string Name {get; set;}
public string Value {get; set;}
public int Prop1 {get; set;}
public double Prop2 {get; set;}
public MyObject (string name, string valueParam, int prop1, double prop2){
this.Name = name;
this.Value = valueParam;
this.Prop1 = prop1;
this.Prop2 = prop2;
}
}
See running on .NET Fiddle . And in Coding Ground . Also I placed GitHub for future reference .
The dictionary has almost identical access time to the array , (at least the access complexity is essentially the same (O (1) in a typical case, but O (N) , which in practice never really comes close to happening).
It is important to note that if you list all elements they can come in any order and if you try to get an element by its index may not see what you are expecting, the algorithm is not stable to give this possibility, even if it works in a basic test will not work otherwise, and the same test that worked may no longer work if you change the Dictionary
or the hash algorithm of the object used as the key. There is no guarantee of anything.
If you need to order use a SortedDictionary
. It is slightly slower but in most cases changes very little and there are many cases that it may be faster than the dictionary. It has complexity O (logN) which is very close to O (1). There are cases where the hash formula may add overhaed which makes it worse than accessing the SortedDictionary
tree. The worst case of it is O (logN), so it is much more predictable and avoids certain types of DOS attacks that the hash allows. And because of the impaired reference locale the hash table of the Dictionary
can access the data more slowly because it does not take advantage of the cache.
If you have to ensure that key values do not repeat you can use Set
, you have some options .
You have another option, KeyedCollection
that gives you the advantage of the list and the advantage of the dictionary at the same time, it may be the most appropriate for what you want. It uses one of the object's members as a key implicitly.