Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string indexer on custom class

Tags:

c#

indexing

I have a simple class:

public class MyClass
{
  public string MyClassName { get; private set; }
  public string MyClassValue { get; private set; }
}

And I want to hold an array of MyClass objects like this:

MyClass[] myClasses = new MyClass[5];

Is it possible, without creating a "collection" object, to be able to access one of those objects in the array of objects by the string indexer (is that the right terminology)?

For example, if myClasses[2] has the value "andegre" in the MyClassName property, how/can I access it like this:

MyClass andegre = myClasses["andegre"];

Instead of doing something like:

MyClass andegre = myClasses[GetIndexOfOfMyClassName("andegre")];

TIA

like image 384
ganders Avatar asked Nov 06 '12 13:11

ganders


1 Answers

For a custom indexer to work on an existing collection, that collection would need to be a custom collection with the indexer implemented by you, which can be whatever arguments you want to take with whatever logic you want behind it. A custom indexer taking a string is perfectly possible on a custom type.

There is no way to override what indexer is used when you are using a MyClass[] (as in, a native .NET array), all you get is the ordinal indexer.

Alternatively, to query for the data you want you can use LINQ to Objects (referred to as just LINQ) as the other answers have suggested.

like image 167
Adam Houldsworth Avatar answered Oct 14 '22 23:10

Adam Houldsworth