Accessing an element of an array of a class using a member variable instead of an index in C #

Suppose I have a class like

class ABC { int ID; public string Name; public ABC(int i, string str) { ID = i; Name = str; } } 

And declare an array of class ABC. Suppose I also initialized each element using a new keyword. Now I want the class access element to use its member identifier instead of the index based on 0. Make the identifier public if necessary.

 public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ABC[] a = new ABC[3]; a[0] = new ABC(100, "First"); a[1] = new ABC(101, "Second"); a[2] = new ABC(102, "Third"); ABC newobj = a[100]; // where 100 is ID of class ABC } } class ABC { int ID; string Name; public ABC(int i, string str) { ID = i; Name = str; } } 
+4
source share
4 answers

Overloading an indexer in a standard array is not possible in C #. If you need to follow the indexer route, I would suggest using a dictionary or List class that supplies its own indexer.

 class ABCCollection : List<ABC> { public ABC this[int id] { get { return this.Where(abc => abc.ID == id).FirstOrDefault(); } } } 

Then you invoke using ABCCollection [100] to access your element.

0
source

You can use LINQ to get the desired object:

 ABC newobj = a.Where(abc => abc.ID == 100).FirstOrDefault(); 

Which returns null if there is no matching identifier.

As suggested by @Xanatos, you can also use this neat version:

 ABC newobj = a.FirstOrDefault(abc => abc.ID == 100); 

As suggested by @Jon, it would be better to use Dictionary<int, ABC> to store your ABC instances. It provides better performance than ever, iterating through a Collection to find the appropriate identifier. But then the key must be unique, you cannot add two ABC instances with the same identifier:

 var a = new Dictionary<int, ABC>(); a.Add(100, new ABC(100, "First")); a.Add(101, new ABC(101, "Second")); a.Add(102, new ABC(102, "Third")); 

You will access it as follows:

 ABC newobj = a[100]; 
+2
source

Here is the code for working with Dictionary (MSDN) :

 //instantiate it: key is of type int, value is of type string var dict = new Dictionary<int, string>(); //add a few items... dict.Add(100, "First"); dict.Add(101, "Second"); //get item with key '100' var first = dict[100]; 

Hope this helps!

+1
source

You can simply use the LINQ query to solve the problem:

  var newobj = (from data in a where data.ID ==100 select data).Cast<ABC>(); 
0
source

Source: https://habr.com/ru/post/1401131/


All Articles