tags:

views:

87

answers:

3

In the spirit of this question, I'd like to know what Gotchas you've come across in Linq. The reason I'm posting this is because I came across a brain teaser today, and I want to share it with the rest of you.

note: I've posted it as an answer

A: 

I came across this little subtly today

        Dim Activity = (From al In user.ActivityLogs
                        Take 2
                        Select al.ActivityDate
                        Order By ActivityDate Descending)

Although this "works", it calls the "Take" before calling the "Order By", which results in the query returning the "Top 2, Order By Ascending", and then simply reverse orders the two records returned after the fact.

If you want to pull up the last two records in the table, you need to use the following

        Dim Activity = (From al In user.ActivityLogs
                        Select al.ActivityDate
                        Order By ActivityDate Descending).Take(2)

This will Order the call Descending and then grab the Top 2 records.

rockinthesixstring
Don't mean to offend or anything, but I don't think that's really a linq subtlety. I think that's more of a misunderstanding/assumption that LINQ syntax is the same as SQL when in fact it uses its own. Upon seeing the first code section, I would assume it worked that way from the start.
Ocelot20
Maybe subtlety is the wrong word, but when the examples I look at direct me to option A (for VB at least), I didn't think that option B even existed. Besides that.. The SQL equivelant would be `Select Top 2 ActivityDate From ActivityLogs Order By ActivityDate Descending` - notice the "Top 2" comes before the Order By.
rockinthesixstring
A: 

For me, it came mostly in the form of LINQ to SQL, where the generated SQL was something completely different than what I thought it was going to be, mostly because of needed parenthesis around certain conditions. Or, certain keywords weren't supported like I expected them too.

Additionally, dealing with the context related to the generated objects was an eye opener when I started initially with LINQ too.

Lastly one developer embedded calculation logic into a LINQ query, and that made it harder to figure out where a calculation went wrong... mostly that's a design issue, but LINQ helped to complicate the process...

Brian
A: 

The biggest gotcha I came across was the horrible lack of debugger support. Basically, when it works, Linq is nice. But when it doesn't, it is harder to debug than assembly. For instance, I've tried to use it to get data out of an Excel XML file. It worked on my simple testcases, but on some input it just threw a null pointer exception. You have to do a binary search just to find the offending row, and that can take hours.

MSalters