C# – Debugging LINQ Queries

c++debugginglinq

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?

Best Solution

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.