通过唯一ID从集合中获取项目

Dav*_*och 2 c# asp.net collections c#-3.0

我有一个继承自CollectionBase的联系人集合:

public class ContactCollection : CollectionBase{
    //...
}
Run Code Online (Sandbox Code Playgroud)

集合中的每个联系人都有一个唯一的ID:

public class Contact{
    public int ContactID{
        get;
        private set;
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

我想我想做的事情如下:

// 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();
Run Code Online (Sandbox Code Playgroud)

可能有更好的方法......如果是这样,请提出建议.

kem*_*002 10

对于初学者,我会改变CollectionBase并使用List<T>.CollectionBase是一个1.0添加,由于泛型而不再需要.实际上,您可能甚至不需要您的ContactCollection课程,因为您可能需要的大多数方法已经在泛​​型实现中实现.

然后你可以使用LINQ:

var item = Collection.FirstOrDefault(x => x.Id == 15);
Run Code Online (Sandbox Code Playgroud)

如果你想保留这些,那么你可以让你的ContactCollection类只是一个包装器List<T> 然后你实际上必须编写的代码将是最小的,因为泛型将完成大部分工作.

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();
Run Code Online (Sandbox Code Playgroud)