3

List of operations obtaining the index of a list

 2 years ago
source link: https://www.codesd.com/item/list-of-operations-obtaining-the-index-of-a-list.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

List of operations obtaining the index of a list

advertisements

I have a class in my Windows application like so:

public class Pets
{
  String Name {get;set;}
  int Amount {get;set;}
}

In one of my other classes i made a List of that class like so.

List<Pets> myPets = new List<Pets>();
myPets.Add(new Pets{ Name = "Fish", Amount = 8});
myPets.Add(new Pets{ Name = "Dogs", Amount = 2});
myPets.Add(new Pets{ Name = "Cats", Amount = 2});

Is there a way i can get the Index of the Pets whos Name = "Fish"?

I realize i can do this

int pos = 0;

for(int x = 0; x<myPets.Count;x++)
{
    if( myPets[x].Name == "Fish")
    {
        pos = x;
    }
}

But in the case that i have ALOT of items in myPets it would take long to loop through them to find the one i am looking for. Is there another way to complete the task above. That would make my application run quicker? In the case that myPets has a lot of items in it.


If you want to find index only to access item of List you can use Dictionary instead.

var pets = new Dictionary<string, int>();
pets.Add("Dogs", 2);
pets.Add("Fish", 8);
int amount = pets["Fish"];


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK