开发者

Can I reference an object within a collection by it's name?

I have a Collection object (b开发者_如何转开发ased on System.Collections.CollectionBase) but to access the values of objects within that collection, I have to use the index currently. Is it possible to get the values based on the name of the object within the collection?

For example, instead of...

MyCollection[0].Value

... how can I do something along the lines of:

MyCollection["Birthday"].Value


In order to do this you would need to have a Dictionary<string,object>. Unfortunately collections only allow random access by index.

You could do something like this:

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

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

But this will be nowhere near as efficient as random access by index.


You could use a Dictionary<TKey, TValue> which allows you to access its element by a key. So if the key in your example is a string you could use Dictionary<string, TValue>.


Why do you think objects in a collection have names? They don't. What you can do is use a Dictionary<String, SomethingElse> to enable your syntax.


As others has said, you need a Dictionary<> to do that. If you cannot change the code that provides the collection, you can use LINQ's ToDictionary() method to convert it to a dictionary yourself:

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

From there on, you can do:

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


You could use the this[] accessor

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

Have this getter property on your MyCollectionClass


One workaround could be

private const int BIRTHDAY = 0;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜