I have to work on some code that’s using generic lists to store a collection of custom objects.
Then it does something like the following to check if a given object’s in the collection and do something if so:
List<CustomObject> customObjects; //fill up the list List<CustomObject> anotherListofCustomObjects; //fill it up //... foreach (CustomObject myCustomObject in customObjects) { if (anotherListofCustomObjects.Contains(myCustomObject)) { //do stuff } }
Problem is is taking forever to process 7000 objects like that.
This is not my code – I am just trying to come up options to improve it – Looks to me it would be much faster to use a dictionary to get the stuff by key instead of looping through the whole collection like the above.
Suggestions?
Well, you seem to have answered it yourself? If you need fast query against a set of data, then a dictionary may be better than a flat list (for largish data sizes, which yours is).
You could, for example, use the object as its own key –
Note that the meaning of equality depends on the context. If you are passing in the original reference, then that is fine –
ContainsKeywould do the job. If you have a different but similar-for-the-purposes-of-equality object to compare to, then you’ll need to implement your ownGetHashCode(),Equals(), and ideallyIEquatable<CustomObject>. Either inCustomObjectitself, or in a customIEqualityComparer<CustomObject>.