我有一个列表(List<customers>
),我用它来查找结果。此客户类具有GUID(长字符串),客户名称和其他一些字符串,但是当我搜索一个给定的UUID时,返回匹配的客户对象需要很长时间(长时间意味着毫秒,但很多)
int indx = CustomerList.FindIndex (Customer => Customer.uuid.Equals ("GUID I'm searching"));
问题在于,当我搜索&gt; 50000个元素(导入约束)时,查找所有索引需要30分钟。
有没有办法索引GUID字段,或者从该列表中对其进行排序以使搜索更快? (例如,只是一个ArrayIndex - GUID数组),允许搜索很多元素。
谢谢,
答案 0 :(得分:2)
使用Dictionary
应该更快
var customers = customerList.ToDictionary(x => x.uuid, x => x);
Customer c;
if(customers.TryGetValue("GUID I'm searching", out c))
// customer found
答案 1 :(得分:0)
您应该使用Dictionary<Guid, Customer>
,其中Guid
标识您的特定客户。
然后,您可以使用以下方式找到您的客户:
Customer cust;
dictionary.TryGetValue(GuidHere, out cust);
答案 2 :(得分:0)
您可以通过创建一个字典来创建索引,其中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
}
答案 3 :(得分:0)
除了字典,你还可以对它进行排序,然后做一个像这样的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());
您必须进行测试,看看排序是否值得花费额外费用。