[Mono-list] Optimising some large loops using LINQ question

Paul Johnson paul at all-the-johnsons.co.uk
Wed Apr 24 00:49:20 UTC 2013


Hi,

I'm working on a project that has some very large loops in it that I'd 
like to remove and use some bits of LINQ to speed things up.

The current code looks like this

foreach (Task t in db.getSubscription().Tasks)
{
      if (t.TaskID == task.TaskID)
      {
           foreach (ReadTask rt in db.ReadTasks.ReadTasks)
           {
               if (rt.TaskID == task.TaskID)
               {
                    result = true;
                    break;
               }
           }					
       }
}

db.getSubscription().Tasks and db.ReadTasks.ReadTasks can both be huge, 
so iterating through them could take quite a while.

The LINQ I've come up with looks like this

Task t = db.getSubscription().Tasks.FirstOrDefault(s => s.TaskID == 
task.TaskID);
if (t != null)
{
      ReadTask rt = db.ReadTasks.ReadTasks.FirstOrDefault(s => s.TaskID 
== task.TaskID);
      if (rt != null)
             result = true;
}

Questions are, are these two pieces of code equivalent and should this 
be FirstOrDefault or just First?

Paul
-- 
"Space," it says, "is big. Really big. You just won't believe how 
vastly, hugely, mindbogglingly big it is. I mean, you may think it's a 
long way down the road to the chemist's, but that's just peanuts to 
space, listen..."
Hitch Hikers Guide to the Galaxy, a truly remarkable book!



More information about the Mono-list mailing list