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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With