【问题标题】:c# Find (fast) items in object listc# 在对象列表中查找(快速)项目
【发布时间】:2014-07-15 12:33:06
【问题描述】:

我有一个用于查找结果的列表 (List<customers>)。这个客户类有一个 GUID(长字符串)、客户名称和其他一些字符串,但是当我搜索一个给定的 UUID 时,返回匹配的客户对象需要很长时间(长表示毫秒,但很多)

int indx = CustomerList.FindIndex (Customer => Customer.uuid.Equals ("GUID I'm searching"));

问题是,当我搜索 >50000 个元素(导入约束)时,需要大约 30 分钟才能找到所有索引。

有没有办法为 GUID 字段编制索引,或者从该列表中对其进行排序以加快搜索速度? (例如只是一个 ArrayIndex - GUID 数组),允许搜索很多元素。

谢谢,

【问题讨论】:

  • 你想要一本字典。
  • 出于什么原因您使用字符串作为 Guid,而不是 System.Guid
  • 我使用 System.Guid 创建,但是当我导出 - 导入时我使用字符串。基本上是一样的。

标签: c# list indexing


【解决方案1】:

使用Dictionary 应该更快

var customers = customerList.ToDictionary(x => x.uuid, x => x);

Customer c;

if(customers.TryGetValue("GUID I'm searching", out c)) 
   //  customer found

【讨论】:

    【解决方案2】:

    您应该使用Dictionary<Guid, Customer>,其中每个Guid 标识您的特定客户。

    然后,您可以使用以下方式定位您的客户:

    Customer cust; 
    dictionary.TryGetValue(GuidHere, out cust);
    

    【讨论】:

      【解决方案3】:

      您可以通过创建以 GUID 字符串为键、对象为值的字典来创建索引:

      Dictionary<string, Customer> index = CustomerList.ToDictionary(c => c.uuid);
      

      现在您可以非常快速地查找对象:

      Customer c = index["GUID I'm searching"];
      

      如果您不知道该 guid 是否存在于列表中:

      Customer c;
      if (index.TryGetValue("GUID I'm searching", out c) {
        // now c contains the customer
      } else {
        // not found
      }
      

      【讨论】:

        【解决方案4】:

        除了字典之外,您还可以对其进行排序,然后执行 BinarySearch 类似的操作

        public class CustomerComparer : IComparer<customers>
        {
            public int Compare(customers x, customers y)
            {
                return x.uuid.CompareTo(y.uuid);
            }
        }
        

        现在,无论您在何处使用 CystomerList,在加载后您都需要对其进行排序。如果您在列表中添加更多内容,我相信您需要采取措施,所以只需在所有内容加载后执行此操作,您只需执行一次

        CustomerList.Sort(new CustomerComparer());
        
        //now sorted you can do BinarySearch
        int indx = CustomerList.BinarySearch(new customers() {uuid = "GUID I'm searching"}, new CustomerComparer());
        

        您必须测试排序是否值得额外费用。

        【讨论】:

          猜你喜欢
          • 2013-05-07
          • 1970-01-01
          • 2011-01-22
          • 1970-01-01
          • 2022-11-17
          • 1970-01-01
          • 2020-06-06
          • 2013-01-04
          • 2016-03-17
          相关资源
          最近更新 更多