Thursday, September 20, 2012

Fast list to list Items transfer

I have to store an Object List in entity object List which already contains some items to be updated in Database.
The item count was 50k and default c# method were too slow which we use normally to fill entity framework.

So here is a comparison and a best method based on object list comparison.


Solution 1(Slowest):


foreach (KeyValuePair<long, Item> objItem in FirstList)
                {
                 if (!SecondList.Any(x => x.Id== objItem .Value.Id))
                      {
                            SecondList.Add(objItem.Value);
                      }
               }

Solution 2(Good):

foreach (KeyValuePair<long, Item> objItem in FirstList)
                {
                 if (!SecondList.Contains(objItem.Key))
                      {
                            SecondList.Add(objItem.Value);
                      }
               }

Solution 3(Best):

Create a list of keys say keyList of SecondList.
foreach(long key in  keyList )
                {
                    FirstList.Remove(key);
                }
                SecondList.AddRange( FirstList .Values);

Graphs Comparison (Time in seconds)

Item Count               First List = 50k , Second List = 0


Item Count             First List = 16k , Second List = 17k


Online Graphing