[英]C# data structure: What type of collection should I use?
对于集合中的每个项目,我需要有一个短字符串和几个int16字段。 我想使用字符串字段遍历集合(这意味着我不想使用数字索引进行迭代)。 该馆藏最多约有10件。 感谢您的任何建议。
我认为Dictionary<string, List<int>>
应该可以满足您的需求。
Dictionary<string, List<int>> dictionary = new Dictionary<string, List<int>>();
dictionary.Add("key", new List<int>{1,2,3,4});
...
如果使用.NET 4,并且“ few int16”始终是相同数量的值,那么您可能还希望将Tuple
类视为字典中的值:
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);
我会使用一个Dictionary
这样您就可以使用任意的key- string
对其进行索引。
如果您的意思是循环遍历 ; 那真的没关系,因为所有集合都支持foreach
:
foreach (var item in collection) { ... }
但是,如果您的意思是将其作为索引进行迭代 ,则应由Dictionary
来完成。
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"];
如果集合中的项目很小(小于或等于10个项目),则使用ListDictionary可以提高性能。如果您不确定元素数量或将来元素数量可能会增加,请使用HaybridDictionary 。
请注意,HybridDictionary机制是在集合较小时在内部使用ListDictionary,然后在集合变大时切换到Hashtable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.