C# 按唯一ID从集合中获取项目
我有一个从CollectionBase继承的联系人集合:C# 按唯一ID从集合中获取项目,c#,asp.net,c#-3.0,collections,C#,Asp.net,C# 3.0,Collections,我有一个从CollectionBase继承的联系人集合: public class ContactCollection : CollectionBase{ //... } 集合中的每个联系人都有一个唯一的ID: public class Contact{ public int ContactID{ get; private set; } //... } 我想我想做的事情如下: // get the contact by thei
public class ContactCollection : CollectionBase{
//...
}
集合中的每个联系人都有一个唯一的ID:
public class Contact{
public int ContactID{
get;
private set;
}
//...
}
我想我想做的事情如下:
// 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();
可能有更好的方法……如果是,请提出建议
Contact contact = Contact.GetContactById(15);
ContactCollection contacts = customer.GetContacts();
contacts[contacts.IndexOf(contacts.Find(c => c.Id == contact.Id))] = contact;
这有点好
int id = 15;
ContactCollection contacts = customer.GetContacts();
int index = users.FindIndex(c => c.Id == id)
if (index >= 0) contacts[index] = Contact.GetContactById(id);
对于初学者,我会更改CollectionBase并使用
List
。CollectionBase是一个1.0版本的添加,由于泛型的原因,它不再需要了。实际上,您甚至可能不需要ContactCollection
类,因为您可能需要的大多数方法都已经在泛型实现中实现了
然后您可以使用LINQ:
var item = Collection.FirstOrDefault(x => x.Id == 15);
如果你想保留这些,那么你可以让你的ContactCollection
类只是列表的包装,那么你实际需要编写的代码将是最小的,因为泛型将完成大部分工作
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();
为什么不从CollectionBase中删除继承,并依赖合成的继承呢
这样,与列表上的线性搜索相比,通过唯一ID进行检索的速度非常快
如果每个联系人都有一个ContactID列表,那么从Contacts字典中检索它们也很容易
有关词典的更多信息,请访问:请告诉我。我有C#3.5可供使用。(有人给你的建议打了-1分,WTF?)+1@David-我怀疑(因为不是我),-1是用来提出建议的,既没有提供链接(!)也没有提供示例。-1很可能是因为“如果您使用LINQ,那么这很简单”是一个非常简单的答案,它本身无法解决任何问题。您甚至要求自己澄清。+1用于解决严重的架构问题displayed@David谢谢,我错过了。哇,我刚刚撞坏了IIS。hm.@David如果你想发布你的代码,我们可以看看是否能快速发现问题。我用列表替换了CollectionBase
,并留下了方法(Index
,IndexOf
,Add
,CopyTo
,等等).联系人不会有联系人,客户最多会有10个联系人,平均3个…因此速度在这里不是问题+1.