Tuesday, March 29, 2016

C# Linq - Improving on the loops

3 Examples that does the same thing.


Version 1#   
 foreach (var updatedPage in listofUpdated)  
       {  
         foreach (PagePage existingPage in ExistingPages)  
         {  
           if (existingPage.PageID == updatedPage.id.ToString())  
           {  
             PagePage Page = (PagePage)existingPage.CreateWritableClone();  
             SetPropertiesForPage(Page, updatedPage);  
             updatedPageCount++;  
           }  
         }  
       }  
Version 2#
  ExistingPages.Where(i => listofUpdated.Any(j => j.id.ToString() == i.PageID))  
         .ToList().ForEach(i =>  
         {  
           var clone = (PagePage)i.CreateWritableClone();  
           SetPropertiesForPage(clone, listofUpdated.First(j => j.id.ToString() == i.PageID));  
           updatedPageCount++;
         });  


Version 3# (with Join should be fastest)
 ExistingPages.Join(listofUpdated,  
         x => x.PageID,  
         y => y.id.ToString(),  
         (x, y) => new  
         {  
           ExistingPage = x,  
           updated = y  
         }).ToList().ForEach(i =>  
         {  
           var clone = (PagePage)i.ExistingPage.CreateWritableClone();  
           SetPropertiesForPage(clone, i.updated);  
           Interlocked.Increment(ref updatedPageCount); 
         
         });  
     
      

No comments:

Post a Comment