2017-05-26 145 views
1

我比较两个列表,查看是否包含从其他反之亦然值:来比较不同的两个列表比较快的方式对象

List<customer> NotOnLocal = 
       AllServer.Where(p => !AllLocal.Any(p2 => p2.Reference == p.customerNumber)) 
         .ToList(); 

List<ConnectCustomer> NotOnServer = 
       AllLocal.Where(p => !AllServer.Any(p2 => p2.customerNumber == p.Reference)) 
         .ToList(); 

这似乎很好地工作,但有超过10万个对象在每个比较中都会慢一点。有谁知道是否有更有效的方法来进行比较并返回相应的列表?

回答

2

您可以使用哈希组(假设你是比较字符串)进行快速检查,如果某个值是在集(给你O(1)复杂性,而不是O(N)):

var serverCustomerNumbers = new HashSet<string>(AllServer.Select(c => c.customerNumber)); 
var localReferences = new HashSet<string>(AllLocal.Select(c => c.Reference)); 

现在,如果你需要得到整个客户对象

List<customer> NotOnLocal = 
        AllServer.Where(c => !localReferences.Contains(c.customerNumber)); 

或者您可以使用组操作来获得所需的客户数量

var notLocalCustomerNumbers = serverCustomerNumbers.Except(localReferences); 
+1

没有,可以很好地加快速度(至少为10倍),谢谢:) –