2011-07-24 109 views
0

我有一个Collection对象(基于System.Collections.CollectionBase),但要访问该集合中的对象的值,我必须使用当前的索引。是否有可能根据集合中对象的名称获取值?我可以通过名称引用集合中的对象吗?

例如,而不是...

MyCollection[0].Value 

......我该怎么办沿着线的东西:

MyCollection["Birthday"].Value 

回答

1

您可以使用此[]存取器

public Item this[string name] 
{ 
get 
{ 
    // iterate through the elements of the collection 
    //and return the one that matches with name 
} 
} 

在您的MyCollectionClass上拥有此getter属性

2

你可以使用一个Dictionary<TKey, TValue>它允许您访问其元素由一个键。所以如果你的例子中的键是一个字符串,你可以使用Dictionary<string, TValue>

4

为了做到这一点,你需要有一个Dictionary<string,object>。不幸的是收藏只允许索引随机访问。

你可以做这样的事情:

var item = MyCollection 
       .Where(x => x.SomeProp == "Birthday") 
       .FirstOrDefault(); 

// careful - item could be null here 
var value = item.Value; 

但是,这将是远不一样有效,因为通过索引随机访问。

2

为什么你认为集合中的对象有名字?他们不。你可以做的是使用Dictionary<String, SomethingElse>来启用你的语法。

+0

对不起,我没有说清楚'Name'是作为Collection中对象的属性之一保存的。 – triplestones

2

正如其他人所说,你需要一个Dictionary<>来做到这一点。如果你不能改变它提供收集的代码,你可以使用LINQ的ToDictionary()方法将其转换为一个字典自己:

var dict = MyCollection.ToDictionary(obj => obj.Name); 

从那里,你可以这样做:

var value = dict["Birthday"].Value; 
0

一个解决办法可能是

private const int BIRTHDAY = 0; 

var value = MyCollection["Birthday"].Value; 
相关问题