Get Item from Collection by unique ID

asp.net, c#, c#-3.0, collections

Solution

For starters I would change out CollectionBase and use `List<T>`. CollectionBase was a 1.0 addition that is no longer needed because of Generics. Actually, you might not even need your `ContactCollection` class, as most of the methods you'll probably need will already be implemented in the generics implementation.

Then you can use LINQ:

var item = Collection.FirstOrDefault(x => x.Id == 15);

And if you want to keep these, then you can have your `ContactCollection` class just be a wrapper for the `List<T>` Then the code you actually have to write will be minimal as the generic will do most of the work.

Contact myPerson = Contact.GetContactById(15);

// get all contacts for the customer
ContactCollection contacts = customer.GetContacts();

// replaces the contact in the collection with the 
// myPerson contact with the same ContactID.
contacts.ReplaceAt(myPerson);

// saves the changes to the contacts and the customer
// customer.Save();

Problem

I have a collection of Contacts that inherits from CollectionBase: ``` public class ContactCollection : CollectionBase{ //... } ``` each contact in the collection has a unique ID: ``` public class Contact{ public int ContactID{ get; private set; } //... } ``` I think what I would like to do is something like the following: ``` // get the contact by their unique [Contact]ID Contact myPerson = Contact.GetContactById(15); // get all contacts for the customer ContactCollection contacts = customer.GetContacts(); // replaces the contact in the collection with the // myPerson contact with the same ContactID. contacts.ReplaceAt(myPerson); // saves the changes to the contacts and the customer // customer.Save(); ``` There is probably a better way...if so, please suggest it.

Original source