Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging LINQ Queries

Tags:

We've been doing a lot of work with LINQ lately, mainly in a LINQ-to-Objects sense. Unfortunately, some of our queries can be a little complicated, especially when they start to involve multiple sequences in combinations. It can be hard to tell exactly what's going on, when you get queries that start to look like:

IEnumerable<LongType> myCompanies =       relevantBusiness.Children_Companies
            .Select(ca => ca.PR_ContractItemId)
            .Distinct()
            .Select(id => new ContractedItem(id))
            .Select(ci => ci.PR_ContractPcrId)
            .Distinct()
            .Select(id => new ContractedProdCompReg(id))
            .Select(cpcr => cpcr.PR_CompanyId)
            .Distinct();

var currentNewItems = myCompanies 
                .Where(currentCompanyId => !currentLic.Children_Appointments.Select(app => app.PR_CompanyId).Any(item => item == currentCompanyId))
                .Select(currentId => new AppointmentStub(currentLic, currentId))
                .Where(currentStub=>!existingItems.Any(existing=>existing.IsMatch(currentStub)));


Items = existingItems.Union(newItems).ToList();

etc., etc...

Even when you debug, it can be difficult to tell who's doing what to who and when. Short of gratuitously calling "ToList" on sequences to get things I can examine more easily, does anyone have any good suggestions for how to debug "complicated" LINQ?

like image 637
GWLlosa Avatar asked Jun 04 '09 20:06

GWLlosa


Video Answer


2 Answers

A query like that seems to indicate to me that you're not doing a good job choosing appropriate data structures, or doing a good job with encapsulation and separation of tasks. I'd suggest taking a look at it and breaking it up.

In general, though, if I want to debug a LINQ query that isn't obviously correct, I'd break it up into subqueries and examine the results one-at-a-time in the debugger.

like image 192
mqp Avatar answered Sep 20 '22 11:09

mqp


I know my answer is "a bit" late, but I had to share this:

Just discovered LinqPad and it's AMAZING (not to mention free).
Can't believe I've written Linq for so long without knowing about this tool.

As far as I understand, it's the work of the author(s?) of O'Reilly's "C# 3.0 in a Nutshell" and "C# 4.0 in a Nutshell" .

like image 40
Cristian Diaconescu Avatar answered Sep 18 '22 11:09

Cristian Diaconescu