【问题标题】:Get Item from Collection by unique ID通过唯一 ID 从集合中获取项目
【发布时间】:2010-04-27 14:57:23
【问题描述】:

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

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();

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

【问题讨论】:

    标签: c# asp.net c#-3.0 collections


    【解决方案1】:

    对于初学者,我会更改 CollectionBase 并使用 List<T>。 CollectionBase 是 1.0 的新增功能,由于泛型而不再需要。实际上,您甚至可能不需要您的 ContactCollection 类,因为您可能需要的大多数方法已经在泛​​型实现中实现了。

    那么你就可以使用LINQ了:

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

    如果你想保留这些,那么你可以让你的 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();
    

    【讨论】:

    • +1 用于解决显示的严重架构问题
    • @David 谢谢,我错过了。
    • 哇,我刚刚崩溃了 IIS。嗯。
    • @David 如果您想发布您的代码,我们可以看看我们是否可以快速发现问题。
    • 我已将 CollectionBase 替换为 List<Contact> 并离开了方法(Index、IndexOf、Add、CopyTo 等)。
    【解决方案2】:
    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);
    

    【讨论】:

    • 请告诉我。我可以使用 C# 3.5。 (有人给了你一个-1的建议,WTF?)+1
    • @David - 我怀疑(因为不是我)-1 是为了在没有提供链接(!)或示例的情况下提出建议。
    • -1 很可能来自这样一个事实,即“如果您使用的是 LINQ,那么这很简单”是一个非常简单的答案,它本身并不能解决任何问题。你甚至要求自己澄清。
    【解决方案3】:

    为什么不从 CollectionBase 中移除继承,并依赖于一个复合的Dictionary?

    这样,与对列表的线性搜索相比,通过唯一 ID 检索接近于 O(1) operation,即非常快。

    如果每个联系人也有一个联系人 ID 列表,那么从联系人字典中检索它们也很容易。

    有关字典的更多信息,请访问:http://dotnetperls.com/dictionary-keys

    【讨论】:

    • 联系人不会有联系人,客户拥有的联系人最多约为 10 次,平均为 3 次……所以这里的速度不会成为问题。 +1
    猜你喜欢
    • 2015-05-21
    • 2018-09-11
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2013-07-29
    • 2018-05-15
    相关资源
    最近更新 更多