简体   繁体   English

继承清单 <T> ,希望通过字符串ID值而不是索引来检索项目

[英]Inheriting List<T>, want items to be retrieved by string ID value instead of index

I have a class called Question. 我有一堂课,叫做问题。 I have another class called Questions which is simply an inheritance of List creating a collection. 我还有一个名为Questions的类,它只是List创建集合的继承。

How can I make it so I can retrieve a Question object by it's ID property instead of the integer based index like this?: 如何做到这一点,以便我可以通过其ID属性而不是像这样的基于整数的索引来检索Question对象?:

Question q = Questions["someidhere"];

Basically I'm looking for the same functionality as a SqlDataReader object where you can retrieve a field based on the field name OR the index. 基本上,我在寻找与SqlDataReader对象相同的功能,您可以在其中基于字段名称或索引来检索字段。

Don't use a List<T> at all; 根本不要使用List<T> use a Dictionary<K,V> 使用Dictionary<K,V>

var dict = new Dictionary<string, Question>();
dict.Add("someidhere", new Question(...));
// ...
var q = dict["someidhere"];

Use Dictionary<TKey, TValue> . 使用Dictionary<TKey, TValue> This will do what you need it to do. 这将完成您需要做的事情。

you can use OrderedDictionary for this purpose. 您可以为此使用OrderedDictionary OrderedDictionary represents a collection of key/value pairs that are accessible by the key or index. OrderedDictionary表示键/索引可访问的键/值对的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM