C# data structure: What type of collection should I use?
For each item in the collection, I need to have a short string and a few int16 fields. I want to iterate through the collection using the string field (meaning I don't 开发者_JAVA百科want to use numeric index to iterate). The collection is at most about 10 items. Thanks for any suggestions.
I think Dictionary<string, List<int>>
should work for you needs.
Dictionary<string, List<int>> dictionary = new Dictionary<string, List<int>>();
dictionary.Add("key", new List<int>{1,2,3,4});
...
If you use .NET 4 and the "few int16" are always the same number of values you might also want to consider the Tuple
class as value in the dictionary:
var map = new Dictionary<string, Tuple<Int16, Int16, Int16>>();
map["Foo"] = Tuple.Create(1, 2, 3);
var values = map["Foo"];
Console.WriteLine("{0} {1} {2}", value.Item1, value.Item2, value.Item3);
I would use a Dictionary
so you can index into it using an arbitrary key - string
, in your case.
If you mean iterate as looping thru; then it really does not matter because all collections support foreach
:
foreach (var item in collection) { ... }
However, if you mean iterate as indexing, then a Dictionary
should do the job.
class SomeFields { public int a; public int b; ... }
var collection = new Dictionary<string, SomeFields>();
collection.Add("name", new SomeFields() { a = 1, b = 2 });
var fields = collection["name"];
If the items in the collection is small "10 items or less" then better for performance to use ListDictionary, If you are not sure about the elements count or if the element count maybe increase in the future then use HaybridDictionary.
Note that HybridDictionary mechanism is to use internally a ListDictionary while the collection is small, and then switching to a Hashtable when the collection gets large.
精彩评论