[Mono-list] Optimising some large loops using LINQ question
andy at brdstudio.net
Wed Apr 24 12:42:55 UTC 2013
If you do not need to work with a piece of data from a database my
suggestion is always don't ask for it thus eliminating the need for the
loop all together. Let the database do the work databases are good at.
It looks like your not even after any of the data but only to see if the
task id exist in one of two tables and/or databases.
I may not understand your issue making my reply invalid, however I'll
make my suggestion anyways.
I'm not very good with LINQ but if you are any good at SQL something
along the lines of a view or stored procedure like the SQL below. If
your database is designed and indexed well your result set should return
in well under 1 second. Then base your return value on weather or not
you have results.
SELECT TOP 1 S.TaskID FROM Subscription S WITH(NOLOCK) WHERE S.TaskID =
SELECT TOP 1 RT.TaskID FROM ReadTasks RT WITH(NOLOCK) WHERE RT.TaskID =
On 4/23/2013 8:49 PM, Paul Johnson wrote:
> 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;
> 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 ==
> 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?
.NET & SQL Server Developer
Home: (269) 244-5237
Cell: (269) 816-2095
Email: andy at brdstudio.net
More information about the Mono-list