Use a string pointer in a custom class

I have a simple class:

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

And I want to save an array of MyClass objects as follows:

 MyClass[] myClasses = new MyClass[5]; 

Is it possible, without creating a collection object, to be able to access one of these objects in an array of objects using a row indexer (is this the correct 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

+6
source share
3 answers

Welcome to the world of LINQ!

 MyClass andegre = myClasses.FirstOrDefault(item => item.MyClassValue.Equals("andegre")); 
+1
source

In order for the custom indexer to work with the existing collection, this collection had to be a non-standard collection with indexer implemented by you, which could be any arguments that you want to take with any logic that you want behind. A custom indexer taking a string is entirely possible in a custom type.

It is not possible to override which index is used when you use MyClass[] (as in, your own .NET array), all you get is an ordinal index.

As an alternative to querying the right data, you can use LINQ to Objects (called only LINQ), as other answers suggested.

+3
source

MyClass[] myClasses is an array (in fact, a vector). Arrays / vectors do not have any row indexer - only positional access.

To get what you want, you need something like a dictionary, for example:

 var myClasses = new Dictionary<string,MyClass>(); myClasses.Add("Fred", new MyClass {...}); myClasses.Add("Betty", new MyClass {...}); myClasses.Add("Wilma", new MyClass {...}); // etc 

then

 MyClass obj = myClasses["Fred"]; 

or

 MyClass obj; if(myClasses.TryGetValue("Fred", out obj)) { // found Fred - use obj } else { // no Fred here - don't look at obj } 
+3
source

All Articles