views:

110

answers:

2

LINQ to SQL .Count takes way to much process time and decreases performances.

I am doing a recursive loop and for one child (lets call it parent) I have to check the number of children under it to make a decision if it should be included or not.

The Count is too slow 8 ms :( for 120 parent records.

Any ideas to make it quicker.

+2  A: 

You could select a projection from your database getting the parent and the count of child element it has. This avoids round tripping to the database.

var query = from x in DataContext.Parents 
            select new {Parent = x, Count = x.Childs.Count() };

Now loop over the results and to whatever you want to next.

If you just want to filter (=where clause) based on the child element count, do it like this:

var query = from x in DataContext.Parents 
            where c.Childs.Count() > 10
            select x;

Linq to SQL will try to translate your calls to IEnumerable.Count() to a SELECT COUNT(*), which should be pretty performant.

Johannes Rudolph
+2  A: 

To me it sounds like you are looping over a result set, doing another Linq-to-sql query for each result. In that case it is bound to be slow since you will be doing a lot of extra database roundtrips.

You will have to rewrite your question to get the children count together right away in the first query.

Anders Abel
Na not doing another Linq-to-sqlThere is the parent and the children entity sets
soldieraman
Just calling `Count()` on the children reference is indeed another linq-to-sql query (although a very simple one) that will result in another sql query roundtrip to the database.
Anders Abel
Alright can you suggest a better way to resolve it?
soldieraman
@Johannes Rudolph has an excellent code example in his answer, using `select new` to get both the parent entity and the child count.
Anders Abel