user1775297
user1775297

Reputation: 87

List operations getting a list's index

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.

Upvotes: 3

Views: 129

Answers (2)

Strelok
Strelok

Reputation: 51441

The way you have your data structured at the moment does not lend itself well to searching by pet's name if the list is large.

So iterating manually like you suggest and what FindIndex is doing is known as a linear search which is a brute force algorithm. If you have N items in your collection, the worst case scenario to find an item is N iterations. This is known as O(N) using the Big O Notation. The speed of search grows linearly with the number of items within your collection.

For faster searching you need to change to a different data structure (like a Hashtable), use a database or implement a different search algorithm, such as a binary search( O(log(n)) complexity ).

Have a look at this question for an example: Can LINQ use binary search when the collection is ordered?

Upvotes: 2

x2.
x2.

Reputation: 9668

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"];

Upvotes: 1

Related Questions