简体   繁体   English

改善查询

[英]Improve the query

I have two List. 我有两个清单。 One with new objects, lets call it NewCol, and one that I have read out of my database(lets call it CurrentCol). 一种带有新对象,我们称它为NewCol,另一种是我从数据库中读出的(叫它CurrentCol)。 The CurrentCol is about 1.2 million rows(and will grow daily) and the NewCol can be any thing from 1 to thousands of rows at a time. CurrentCol大约有120万行(并且每天都会增长),NewCol一次可以是1到数千行。 Can any one please help me improve the following code as it runs way too slow: 谁能帮我改善以下代码,因为它运行太慢:

foreach (PortedNumberCollection element in NewCol)
{
    if (CurrentCol.AsParallel().Select(x => x.MSISDN).Contains(element.MSISDN))
    {
        CurrentCol.AsParallel().Where(y => y.MSISDN == element.MSISDN)
            .Select
                (x =>
                    {      
                       //if the MSISDN exists in both the old and new collection
                       // then update the old collection                                              
                       x.RouteAction = element.RouteAction;
                       x.RoutingLabel = element.RoutingLabel;
                       return x;
                    }
                 );
    }
    else
    {
        //The item does not exist in the old collection so add it
        CurrentCol.Add(element);
    }
}

It's a pretty bad idea to read the whole database into memory and search it there. 将整个数据库读入内存并在其中搜索是一个非常糟糕的主意。 Searching is what databases are optimized for. 搜索是针对数据库进行优化的。 The best thing you can do is to move that whole code into the database somehow, for example by executing a MERGE statement for each item in NewCol . 最好的办法是将整个代码以某种方式移到数据库中,例如,通过对NewCol每个项目执行MERGE语句。


However, if you can't do that, the next best thing would be to make CurrentCol a dictionary with MSISDN as the key: 但是,如果您不能这样做,那么下一个最好的办法就是使CurrentCol成为以MSISDN为键的字典:

// Somewhere... Only once, not every time you want to add new items
// In fact, there shouldn't be any CurrentCol, only the dictionary.
var currentItems = CurrentCol.ToDictionary(x => x.MSISDN, x => x);

// ...

foreach(var newItem in NewCol)
{
    PortedNumberCollection existingItem;
    if(currentItems.TryGetValue(newItem.MSISDN, out existingItem)
    {
        existingItem.RouteAction = newItem.RouteAction;
        existingItem.RoutingLabel = newItem.RoutingLabel;
    }
    else
    {
        currentItems.Add(newItem.MSISDN, newItem);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM