3

If I have

List<MyClass> MyObj;

I can access specific member like this:

MyObj[0] = new MyClass();

But some time ago, somewhere on msdn I have read, that it is possible to access my objects like that:

MyObj["mykey"] = new MyClass();

Is that possible, or am I making things up here?

ojek
  • 9,680
  • 21
  • 71
  • 110

4 Answers4

9

In List it's not possible, because it only has int indexer (this[int index]) which allows to get object by index.

For this you should use Dictionary<string, MyClass>, which will allow you to get objects by key e.g.:

MyDictionary["MyKey"] = new MyClass();

MSDN Dictionary

Zbigniew
  • 27,184
  • 6
  • 59
  • 66
6

Not directly since a List<T> has only an int indexer. However, if you want to lookup an object via a property you could use LINQ:

MyClass obj = MyObj.FirstOrDefault(c => c.SomeProp == "mykey");
if(obj != null)
{
   // yes
}

another approach is to use a Dictionary<string, MyClass>(key must be unique):

MyClass obj;
if(MyObjDictionary.TryGetValue("mykey", out obj))
{
    // yes
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

There are many different types where the indexer takes a string. You were probably looking at a Dictionary.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
3

Well, this may be possible with this override, like :

public class MyClass : List<int> 
{
    public int this[string key] {
        get {
            return this.Where(x=>x==int.Parse(key)).SingleOrDefault();
        }
    }
}

so in code you will use it like:

  var a = new MyClass() {1,2,3,4,5,6,7}; 
  a["5"]; //this will return 5 integer

No need for any dictionary or additional datastructures. Worth mantionig that in this case you may have performance issues on large collections, but if your collection is small enough, go with this.

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123