pauet
pauet

Reputation: 35

c# Find (fast) items in object list

I have a list (List<customers>) that I'm using to find results. This customer class have a GUID (long string), customer name, and some other strings, but when I'm searching for one given UUID it takes so long to return the customer object that matches (long means miliseconds, but a lot)

int indx = CustomerList.FindIndex (Customer => Customer.uuid.Equals ("GUID I'm searching"));

The problem is that when I'm searching >50000 elements (import constraints) it takes like 30 minutes to find all indexes.

Is there a way to index GUID field, or sort it from that list to make the search faster? (for example just a ArrayIndex - GUID array) that allows to search a Lot of elements.

Thanks,

Upvotes: 1

Views: 4949

Answers (4)

CharlesNRice
CharlesNRice

Reputation: 3259

Besides a dictionary you could also sort it and then do a BinarySearch Something like this

public class CustomerComparer : IComparer<customers>
{
    public int Compare(customers x, customers y)
    {
        return x.uuid.CompareTo(y.uuid);
    }
}

Now where ever you are using the CystomerList after it has been loaded you will need to sort it. If you add more to the list I believe you would need to resort so just do it after everything is loaded and you'll only need to do it once

CustomerList.Sort(new CustomerComparer());

//now sorted you can do BinarySearch
int indx = CustomerList.BinarySearch(new customers() {uuid = "GUID I'm searching"}, new CustomerComparer());

You'll have to test to see if the sorting if worth the extra cost.

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Using a Dictionary should be faster

var customers = customerList.ToDictionary(x => x.uuid, x => x);

Customer c;

if(customers.TryGetValue("GUID I'm searching", out c)) 
   //  customer found

Upvotes: 3

Guffa
Guffa

Reputation: 700192

You can make an index by creating a dictionary with the GUID string as key and the object as value:

Dictionary<string, Customer> index = CustomerList.ToDictionary(c => c.uuid);

Now you can look up objects very fast:

Customer c = index["GUID I'm searching"];

If you don't know if the guid exists in the list:

Customer c;
if (index.TryGetValue("GUID I'm searching", out c) {
  // now c contains the customer
} else {
  // not found
}

Upvotes: 0

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149528

You should use a Dictionary<Guid, Customer> where each Guid identifies your specific customer.

Then, you can locate your customer using:

Customer cust; 
dictionary.TryGetValue(GuidHere, out cust);

Upvotes: 0

Related Questions