282

Background: Over the next month, I'll be giving three talks about or at least including LINQ in the context of C#. I'd like to know which topics are worth giving a fair amount of attention to, based on what people may find hard to understand, or what they may have a mistaken impression of. I won't be specifically talking about LINQ to SQL or the Entity Framework except as examples of how queries can be executed remotely using expression trees (and usually IQueryable).

So, what have you found hard about LINQ? What have you seen in terms of misunderstandings? Examples might be any of the following, but please don't limit yourself!

  • How the C# compiler treats query expressions
  • Lambda expressions
  • Expression trees
  • Extension methods
  • Anonymous types
  • IQueryable
  • Deferred vs immediate execution
  • Streaming vs buffered execution (e.g. OrderBy is deferred but buffered)
  • Implicitly typed local variables
  • Reading complex generic signatures (e.g. Enumerable.Join)
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    I would be interested to know when you are going to do these talks, and if there is any way to view them online – Mark Heath Oct 19 '08 at 20:24
  • 2
    First talk: Copenhagen, October 30th. Hopefully this will be taped. (Whole day!) Second talk: London, Nov 19th in the evening, London .NET Users Group, probably on Push LINQ. Third talk: Reading, Nov 22nd, Developer Developer Day, Implementing LINQ to Objects in 60 minutes. – Jon Skeet Oct 19 '08 at 20:34
  • cool, I might see if I can get along to the DDD day in Reading – Mark Heath Oct 19 '08 at 20:51
  • 1
    Downvoters: please add an explanatory comment. – Jon Skeet May 19 '09 at 05:14
  • 2
    @Jon, Sorry, but I need to close this. – Tim Post Aug 20 '11 at 18:27
  • 3
    @Tim: Fair enough - it wasn't getting any more answers anyway. Personally I think it *did* end up being constructive, mind you - I certainly found it useful to see what people find tricky. I probably wouldn't have asked it now though... – Jon Skeet Aug 20 '11 at 18:33
  • @Jon - I can change it to 'too localized' if you like. I have an enumerated list to pick from, I picked the one that I thought fit the best. I'm sure this question will have value for others, it's just not on topic for the Stack Overflow that emerged almost three years after you asked this. – Tim Post Aug 20 '11 at 19:40
  • @Tim: Exactly. Possibly worth migrating to Programmers instead? It's about programmers as people... but also about a specific technology, which makes it a tricky one. I'm really not that picky though, to be honest. – Jon Skeet Aug 20 '11 at 19:47
  • @Jon This has quite a few answers (one accepted), it's nearly three years old and migrating it to another site would not be very constructive. I'm not quite sure how the system could be improved based on this experience. Or rather, I can't articulate any kind of suggested improvement. – Tim Post Aug 20 '11 at 20:06
  • @Tim: Maybe one to ask for opinions on in meta? Or straight to Jeff? I don't know how common it is. – Jon Skeet Aug 20 '11 at 20:18
  • @Jon these are corner cases that really should be addressed, I suggest meta. Remember, Jeff _hates_ email. Touching a question like this induces a sense of trepidation for all of us [moderators], so a consensus would be extremely useful. – Tim Post Aug 20 '11 at 20:25

42 Answers42

271

Delayed execution

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 12
    Righto - this is clearly the favourite amongst readers, which is the most important thing for this question. I'll add "buffering vs streaming" into the mix as well, as that's closely related - and often isn't discussed in as much detail as I'd like to see in books. – Jon Skeet Oct 25 '08 at 19:51
  • 10
    Really? I had it's lazy-loaded nature pointed out to me so many times while learning Linq, it was never an issue for me. – Adam Lassek Dec 17 '08 at 16:19
  • @ALassek, it really depends on where you learn LINQ from. I've presented for user groups where not a one knew than it was lazy evaluated. – JaredPar Dec 17 '08 at 23:44
  • 26
    Agree with ALassek. The MSDN documentation clearly states the lazy evaluation nature of LINQ. Maybe the real problem is the lazy programming nature of the developers... =) – Seiti Dec 18 '08 at 18:30
  • 4
    ... especially when you realize that it applies to LINQ to objects and not just LINQ 2 SQL - when you see 10 web method calls to retrieve a list of items when you're already enumerating through that same list of items and you thought the list was already evaluated – Simon_Weaver Feb 15 '09 at 05:26
  • 1
    This should be deferred execution, right? Anders has mentioned this many times in his videos about LINQ in MSDN's Channel 9. – Eriawan Kusumawardhono Mar 03 '09 at 04:14
  • @eriawan, delayed or deferred works :) – JaredPar Mar 03 '09 at 04:33
  • 5
    Knowing what the yield statement is and how it works is IMHO critical for a thorough understanding of LINQ. – peSHIr Mar 06 '09 at 07:43
  • i have colleagues that, even being told a million times or after reading book in abd book out still don't get the lazy execution behavior of LINQ. – Pauli Østerø Dec 13 '10 at 23:29
  • It seems to be a common misconception that IEnumerable is a lazy list, i.e. only evaluated once.. – Robert Jeppesen Mar 17 '11 at 21:31
125

I know the deferred execution concept should be beaten into me by now, but this example really helped me get a practical grasp of it:

static void Linq_Deferred_Execution_Demo()
{
    List<String> items = new List<string> { "Bob", "Alice", "Trent" };

    var results = from s in items select s;

    Console.WriteLine("Before add:");
    foreach (var result in results)
    {
        Console.WriteLine(result);
    }

    items.Add("Mallory");

    //
    //  Enumerating the results again will return the new item, even
    //  though we did not re-assign the Linq expression to it!
    //

    Console.WriteLine("\nAfter add:");
    foreach (var result in results)
    {
        Console.WriteLine(result);
    }
}

The above code returns the following:

Before add:
Bob
Alice
Trent

After add:
Bob
Alice
Trent
Mallory
dso
  • 9,463
  • 10
  • 53
  • 59
  • 2
    http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx <-- I think this is the best blog to explain it in my opinion. (far out 2007, can't believe it's been around that long already) – Phill Dec 31 '10 at 13:15
104

That there is more than just LINQ to SQL and the features are more than just a SQL parser embedded in the language.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
smaclell
  • 4,568
  • 7
  • 41
  • 49
86

Big O notation. LINQ makes it incredibly easy to write O(n^4) algorithms without realizing it, if you don't know what you're doing.

Benj
  • 31,668
  • 17
  • 78
  • 127
erikkallen
  • 33,800
  • 13
  • 85
  • 120
  • 16
    How about an example? – hughdbrown Nov 09 '09 at 14:54
  • 4
    As far as an example, maybe he means the fact that it is very easy to have a Select clause contain many Sum() operators with each of them causing another pass over the entire recordset. – Rob Packwood Mar 04 '10 at 22:22
  • 1
    In fact it might even be worth going through what big O notation is and why it's important, as well as some examples of inefficient resulting queries. I think that's what the original poster was suggesting, but I thought I'd mention it anyways. -- EDIT: just realised that this post was 1.5 years old :-) – zcrar70 May 14 '10 at 13:41
  • 7
    That wouldn't be O(n^x), that'd be O(xn), which is just O(n). – Malfist Nov 15 '10 at 21:39
  • 3
    Trying to do a join without the join operator will result in O(n^x): from i1 in range1 from i2 in range2 from i3 in range3 from i4 in range4 where i1 == i2 && i3 == i4 select new { i1, i2, i3, i4}. And I've actually seen this written before. It works, but very slowly. – MarkPflug May 02 '11 at 19:18
55

I think the fact that a Lambda expression can resolve to both an expression tree and an anonymous delegate, so you can pass the same declarative lambda expression to both IEnumerable<T> extension methods and IQueryable<T> extension methods.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
Tim Jarvis
  • 18,465
  • 9
  • 55
  • 92
53

Took me way too long to realize that many LINQ extension methods such as Single(), SingleOrDefault() etc have overloads that take lambdas.

You can do :

Single(x => x.id == id)

and don't need to say this - which some bad tutorial got me in the habit of doing

Where(x => x.id == id).Single()
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
40

In LINQ to SQL I constantly see people not understanding the DataContext, how it can be used and how it should be used. Too many people don't see the DataContext for what it is, a Unit of Work object, not a persistant object.

I've seen plenty of times where people are trying to singleton a DataContext/ session it/ etc rather than making a new time for each operation.

And then there's disposing of the DataContext before the IQueryable has been evaluated but that's more of a prople with people not understanding IQueryable than the DataContext.

The other concept I see a lot of confusion with is Query Syntax vs Expression Syntax. I will use which ever is the easiest at that point, often sticking with Expression Syntax. A lot of people still don't realise that they will produce the same thing in the end, Query is compiled into Expression after all.

Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
  • 2
    Warning: Unit of work can be a small program with the data context as a singleton. – graffic Nov 29 '08 at 14:16
  • 15
    You should not use the DataContext in a singleton, it's not thread safe. – Aaron Powell Nov 30 '08 at 04:56
  • 3
    @Slace, not all programs are multitheaded, so it is OK to have the DataContext as a singleton in a lot of "desktop" software – Ian Ringrose Nov 04 '09 at 16:16
  • 2
    I got bitten by this (using DataContext as a singleton) when I did my first LINQ to SQL project. I don't think that the documentation and books make this obvious enough. Actually, I think the name could be improved, but I'm not sure how. – Roger Lipscombe Apr 09 '10 at 06:59
  • 1
    It took reading ScottGu's artivles on Linq multiple times to get this pounded in my head. – Evan Plaice Jun 14 '10 at 20:49
34

I think the misunderstood part of LINQ is that it is a language extension, not a database extension or construct.

LINQ is so much more than LINQ to SQL.

Now that most of us have used LINQ on collections, we will NEVER go back!

LINQ is the single most significant feature to .NET since Generics in 2.0, and Anonymous Types in 3.0.

And now that we have Lambda's, I can't wait for parallel programming!

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Chris
  • 6,702
  • 8
  • 44
  • 60
26

I for one would sure like to know if I need to know what expression trees are, and why.

Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
  • 6
    I think it's worth knowing what expression trees are and why they exist, but not the details of how to build them yourself. (They're a pain to build by hand, but the compiler will do a great job when converting a lambda expression.) – Jon Skeet Oct 19 '08 at 06:39
  • 3
    Actually, I was thinking about doing a few blog entries on expression trees (since I do "get" them). I find manipulating expression trees very useful... – Marc Gravell Oct 19 '08 at 10:03
  • However, I don't think they be helpful for Jon's talk(s) ;-p – Marc Gravell Oct 19 '08 at 10:04
  • I'll need to mention them briefly, but your blog entries would certainly be welcome :) – Jon Skeet Oct 19 '08 at 17:36
  • 3
    I just worry that expression trees are going to be like the yield statement: something that turned out to be incredibly valuable despite the fact that I didn't understand what it was for at first. – Robert Rossney Oct 19 '08 at 18:54
  • 1
    Marc Gravell I'd love to read your blog entries on the subject. Looking forward to it – Alexandre Brisebois Oct 19 '08 at 23:06
  • I have added a post to this chain with a link... – Marc Gravell Oct 20 '08 at 09:09
20

I'm fairly new to LINQ. Here's the things I stumbled over in my first attempt

  • Combining several queries into one
  • Effectively debugging LINQ queries in Visual Studio.
Mark Heath
  • 48,273
  • 29
  • 137
  • 194
  • 21
    Debugging LINQ is a topic all by itself, and an important one. I think the greatest weakness of LINQ is that it lets you write blocks of arbitrarily complex logic that you can't step through. – Robert Rossney Oct 19 '08 at 18:58
  • 3
    these may be a good place to use LINQ pad – Maslow Jul 03 '09 at 18:54
  • 2
    Agree heartily; that's why I wrote [LINQ Secrets Revealed: Chaining and Debugging](http://www.simple-talk.com/dotnet/.net-framework/linq-secrets-revealed-chaining-and-debugging/), just published on Simple-Talk.com, that you may find of assistance. – Michael Sorens Dec 10 '10 at 16:33
  • Yes, LinqPad is a great secondary tool for developing your LINQ queries in. Especially when starting out and you're new to the conventions/patterns. – Buffalo Dec 11 '10 at 23:14
20

Something that I didn't originally realise was that the LINQ syntax doesn't require IEnumerable<T> or IQueryable<T> to work, LINQ is just about pattern matching.

alt text http://bartdesmet.info/images_wlw/QIsIQueryabletheRightChoiceforMe_13478/image_thumb_3.png

Here is the answer (no, I didn't write that blog, Bart De Smet did, and he's one of the best bloggers on LINQ I've found).

Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
19

I still have trouble with the "let" command (which I've never found a use for) and SelectMany (which I've used, but I'm not sure I've done it right)

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • 2
    Any time you want to introduce a variable you would use a let statement. Think of a traditional loop where you are introducing variables within it and giving each variable a name to help the readability of code. Sometimes it is also nice where you have a let statement evaluating a function result, which you can then select and order by on without having to evaluate the result twice. – Rob Packwood Mar 04 '10 at 22:23
  • 'let' allows you to do composite types. Handy stuff. – Phill Dec 31 '10 at 13:20
19

Understanding when the abstraction among Linq providers leaks. Some things work on objects but not SQL (e.g., .TakeWhile). Some methods can get translated into SQL (ToUpper) while others can't. Some techniques are more efficient in objects where others are more effective in SQL (different join methods).

denis phillips
  • 12,550
  • 5
  • 33
  • 47
  • 1
    This is a very good point. It doesn't help that Intellisense will show you ALL of them and it will usually even compile. Then you blow up at runtime. I hope VS 2010 does a better job of showing relevant extension methods. – Jason Short Aug 23 '09 at 00:41
12

Couple of things.

  1. People thinking of Linq as Linq to SQL.
  2. Some people think that they can start replacing all foreach/logic with Linq queries without considering this performance implications.
Krishna Kumar
  • 7,841
  • 14
  • 49
  • 61
11

OK, due to demand, I've written up some of the Expression stuff. I'm not 100% happy with how blogger and LiveWriter have conspired to format it, but it'll do for now...

Anyway, here goes... I'd love any feedback, especially if there are areas where people want more information.

Here it is, like it or hate it...

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
10

Some of the error messages, especially from LINQ to SQL can be pretty confusing. grin

I've been bitten by the deferred execution a couple of times like everyone else. I think the most confusing thing for me has been the SQL Server Query Provider and what you can and can't do with it.

I'm still amazed by the fact you can't do a Sum() on a decimal/money column that's sometimes empty. Using DefaultIfEmpty() just won't work. :(

9

I think a great thing to cover in LINQ is how you can get yourself in trouble performance-wise. For instance, using LINQ's count as a loop condition is really, really not smart.

Steve
  • 11,763
  • 15
  • 70
  • 103
7

That IQueryable accept both, Expression<Func<T1, T2, T3, ...>> and Func<T1, T2, T3, ...>, without giving a hint about performance degradation in 2nd case.

Here is code example, that demonstrates what I mean:

[TestMethod]
public void QueryComplexityTest()
{
    var users = _dataContext.Users;

    Func<User, bool>                funcSelector =       q => q.UserName.StartsWith("Test");
    Expression<Func<User, bool>>    expressionSelector = q => q.UserName.StartsWith("Test");

    // Returns IEnumerable, and do filtering of data on client-side
    IQueryable<User> func = users.Where(funcSelector).AsQueryable();
    // Returns IQuerible and do filtering of data on server side
    // SELECT ... FROM [dbo].[User] AS [t0] WHERE [t0].[user_name] LIKE @p0
    IQueryable<User> exp = users.Where(expressionSelector);
}
Valera Kolupaev
  • 2,285
  • 14
  • 14
6

I don't know if it qualifies as misunderstood - but for me, simply unknown.

I was pleased to learn about DataLoadOptions and how I can control which tables are joined when I make a particular query.

See here for more info: MSDN: DataLoadOptions

Martin
  • 2,865
  • 4
  • 24
  • 22
6

I would say the most misunderstood (or should that be non-understood?) aspect of LINQ is IQueryable and custom LINQ providers.

I have been using LINQ for a while now and am completely comfortable in the IEnumerable world, and can solve most problems with LINQ.

But when I started to look at and read about IQueryable, and Expressions and custom linq providers it made my head spin. Take a look at how LINQ to SQL works if you want to see some pretty complex logic.

I look forward to understanding that aspect of LINQ...

Jack Ukleja
  • 13,061
  • 11
  • 72
  • 113
6

As most people said, i think the most misunderstood part is assuming LINQ is a just a replacement for T-SQL. My manager who considers himself as a TSQL guru would not let us use LINQ in our project and even hates MS for releasing such a thing!!!

HashName
  • 651
  • 7
  • 17
  • Too many people use it as a replacement for TSQL. Most of them have never heard of an execution plan. – erikkallen May 27 '09 at 21:03
  • +1 because I agree with your manager, at least insofar as allowing LINQ to SQL in any project. LINQ to Objects is another matter entirely. – NotMe Sep 30 '10 at 14:26
5

How easy it is to nest a loop is something I don't think everyone understands.

For example:

from outerloopitem in outerloopitems
from innerloopitem in outerloopitem.childitems
select outerloopitem, innerloopitem
Rob Packwood
  • 3,698
  • 4
  • 32
  • 48
5

What does var represent when a query is executed?

Is it iQueryable, iSingleResult, iMultipleResult, or does it change based on the the implementation. There's some speculation about using (what appears to be) dynamic-typing vs the standard static-typing in C#.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
user31939
  • 263
  • 1
  • 3
  • AFAIK var always is the concrete class in question (even if it's an anonymous type) so it's *never* IQueryable, ISingleResult or anything beginning with 'I' (concrete classes that begin with 'I' need not apply). – Motti Dec 09 '08 at 07:25
4

Compiled Queries

The fact that you can't chain IQueryable because they are method calls (while still nothing else but SQL translateable!) and that it is almost impossible to work around it is mindboggling and creates a huge violation of DRY. I need my IQueryable's for ad-hoc in which I don't have compiled queries (I only have compiled queries for the heavy scenarios), but in compiled queries I can't use them and instead need to write regular query syntax again. Now I'm doing the same subqueries in 2 places, need to remember to update both if something changes, and so forth. A nightmare.

Community
  • 1
  • 1
Alex
  • 75,813
  • 86
  • 255
  • 348
4

group by still makes my head spin.

Any confusion about deferred execution should be able to be resolved by stepping through some simple LINQ-based code and playing around in the watch window.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
  • 1
    I've found that implementing quite a bit of LINQ to Objects for fun really helps :) But yes, it is a bit confusing - certainly if I haven't done any LINQ for a while I have to go back to the signatures. Likewise "join" vs "join into" often gets me... – Jon Skeet Nov 26 '08 at 17:17
4

I think the #1 misconception about LINQ to SQL is that you STILL HAVE TO KNOW SQL in order to make effective use of it.

Another misunderstood thing about Linq to Sql is that you still have to lower your database security to the point of absurdity in order to make it work.

A third point is that using Linq to Sql along with Dynamic classes (meaning the class definition is created at runtime) causes a tremendous amount of just-in-time compiling. Which can absolutely kill performance.

NotMe
  • 87,343
  • 27
  • 171
  • 245
  • 4
    It is very beneficial to already know SQL, however. Some SQL that is emitted by Linq to SQL (and other ORM's) can be downright dubious, and knowing SQL helps diagnose such problems. Also, Linq to SQL can make use of stored procedures. – Robert Harvey Sep 30 '10 at 14:35
2

Lazy Loading.

Ryan Eastabrook
  • 4,085
  • 5
  • 30
  • 35
  • similar to http://stackoverflow.com/questions/215548/whats-the-hardest-or-most-misunderstood-aspect-of-linq/215562#215562 – Pratik Oct 07 '11 at 15:57
2

As most people said, i think the most misunderstood part is assuming LINQ is a just a replacement for T-SQL. My manager who considers himself as a TSQL guru would not let us use LINQ in our project and even hates MS for releasing such a thing!!!

stackuser1
  • 213
  • 2
  • 6
  • 18
2

Transactions (without using TransactionScope)

Naeem Sarfraz
  • 7,360
  • 5
  • 37
  • 63
2

As mentioned, lazy loading and deferred execution

How LINQ to Objects and LINQ to XML (IEnumerable) are different from LINQ to SQL(IQueryable)

HOW to build a Data Access Layer, Business Layer, and Presentation Layer with LINQ in all layers....and a good example.

Ash Machine
  • 9,601
  • 11
  • 45
  • 52
  • The first two I can do. I wouldn't like to try doing the third yet in a "this is the right way to do it" sense... – Jon Skeet Jan 07 '09 at 17:52
  • +1, until you pointed it out, I hadn't realized that LINQ-to-Objects and LINQ-to-XML were IEnumerable as opposed to LINQ-to-SQL as IQueryable, but it makes sense. Thanks! – Pretzel May 13 '10 at 15:57
1

I think you should give more attention to the most commonly used features of LINQ in detail - Lambda expressions and Anonymous types, rather than wasting time on "hard to understand" stuff that is rarely used in real world programs.

user21582
  • 190
  • 3
  • 6
  • 4
    I agree with the principle, but in reality almost all of the hard-to-understand bits *are* used frequently in real world programs - just without people really understanding them. – Jon Skeet Oct 19 '08 at 06:37
1

Which is faster, inline Linq-to-Sql or Linq-to-Sql using Tsql Sprocs

... and are there cases where it's better to use server-side (Sproc) or client-side (inline Linq) queries.

user31939
  • 263
  • 1
  • 3
1

Comprehension syntax 'magic'. How does comprehension syntax gets translated into method calls and what method calls are chosen.

How does, for example:

from a in b
from c in d
where a > c
select new { a, c }

gets translated into method calls.

Pop Catalin
  • 61,751
  • 23
  • 87
  • 115
  • I did a little bit of this in the talk, but mostly just "this is the *sort* of thing the compiler does" - including "it doesn't know that the translation will call extension methods etc". The details are pretty complicated, of course... – Jon Skeet Nov 04 '08 at 15:26
  • (I did include a bit on transparent identifiers though, which is relevant to your example.) – Jon Skeet Nov 04 '08 at 15:27
  • I always find it easier to understand if I try to rethink it as a method chain: b.SelectMany(a => d, (a,c) => new { a=a, c=c }).Where(thing => thing.a > thing.c).Select(otherthing => new {a=otherthing.a, c=otherthing.c} ) – JerKimball Mar 02 '10 at 19:29
1

For LINQ2SQL : Getting your head around some of the generated SQL and writing LINQ queries that translate to good (fast) SQL. This is part of the larger issue of knowing how to balance the declarative nature of LINQ queries with the realism that they need to execute fast in a known environment (SQL Server).

You can get a completely different SQL generated query by changing a tiny tiny thing in the LINQ code. Can be especially dangerous if you are creating an expression tree based on conditional statements (i.e. adding optional filtering criteria).

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
1

I find it a bit disappointing that the query expression syntax only supports a subset of the LINQ functionality, so you cannot avoid chaining extension methods every now and then. E.g. the Distinct method cannot be called using the query expression syntax. To use the Distinct method you need to call the extension method. On the other hand the query expression syntax is very handy in many cases, so you don't want to skip that either.

A talk on LINQ could include some practical guidelines for when to prefer one syntax over the other and how to mix them.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • Personally I'm glad that the query expression syntax doesn't include very many operators. The dot notation is fine when you need to use it, and this balance keeps C# still a *reasonably* small language. The query expression part of the spec is nice and short - I wouldn't want a really long section. – Jon Skeet Dec 20 '08 at 19:39
1

How LINQ to SQL translate it!

Suppose that we have a table with 3 fields; A, B & C (They are integers and table name is "Table1").
I show it like this:
[A, B, C]

Now we want to get some result such as this:
[X = A, Y = B + C]

And we have such a class:

public class Temp
{
   public Temp(int x, int y)
   {
      this.X = x;
      this.Y = y;
   }

   public int X { get; private set; }
   public int Y { get; private set; }
}

Then we use it like this:

using (MyDataContext db = new MyDataContext())
{
   var result = db.Table1.Select(row => 
                   new Temp(row.A, row.B + row.C)).ToList();
}

The generated SQL query is:

SELECT [t0].[A] AS [x], [t0].[B] + [t0].[C] AS [y]
FROM [Table1] AS [t0]

It translates the .ctor of the Temp. It knows that I want "row.B + row.C" (even more...) to put on the "y" paramter of my class constructor!

These translations are very intrested to me. I like that and I think writing such translators (LINQ to Something) is a little hard!

Of course! It's a bad news: the LINQ to Entities (4.0) does not support constructors with parameters. (Why not?)

Amir Karimi
  • 5,401
  • 4
  • 32
  • 51
1

I find "Creating an Expression Tree" to be tough. There are many things that bug me w.r.t what you can to with LINQ, LINQ to SQL and ADO.Net altogether.

iTSrAVIE
  • 846
  • 3
  • 12
  • 26
1

Explain why Linq does not handle left outer join as simple as in sql syntax. See this articles: Implementing a Left Join with LINQ, How to: Perform Left Outer Joins (C# Programming Guide) I got so disappointed when I came across this obstacle that all my respect for the language vanished and I decedid that it was just something that quickly would fade away. No serious person would want to work with a syntax that lacks these battlefield proven primitives. If you could explain why these sort of set operation are not supported. I would become a better and more openminded person.

Patrik Lindström
  • 1,057
  • 3
  • 13
  • 23
  • 1
    interesting. I haven't found a need for the Left Outer join in Linq so far. Can you provide situations where this would be the best choice and how it would benifit the execution of the query ? – Alexandre Brisebois Mar 07 '11 at 15:00
  • 1
    Left outer joins don't make sense in the context of object relational mapping (which is what LINQ does). Objects shouldn't be hydrated with all their fields set to null! – Billy ONeal Mar 07 '11 at 19:06
  • But at the time everyone spoke how Linq now totally should replace SQL. Only old stubborn people use sql and stored procedure I was told. I was building a website where the economy dept people where matching (reconsiliating) external invoices with internal accounting. Eg we got an invoice for a subcontracter who worked at project. The subcontracter Name matches, the activitity matches the client mathces but Project code does not matches. Something has to be done. Guess who is the project leader contact them, contact the subcontracter etd. So this is a left join al lot application. – Patrik Lindström Apr 14 '11 at 14:26
  • 1
    I like your inclusion of left join here, I didn't want to double post. Your dismissal of LINQ otherwise is heavy-handed. I'd like to see left-join as an operator or something too, but I still use LINQ all the time. Beats the hell out of the old way. – Jason Kleban May 10 '11 at 19:03
  • I am now more openminded and use Linq. I even try to only use Linqpad for day to day adhoc database queries. But now it is group by in Linq that confuses me. (see eg http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/) Its like now I get it and no i dont. – Patrik Lindström Dec 15 '11 at 20:14
1

I have found hard to find clear information about Anonymous types specially in regard of performances in web application. Also I would suggest better and practical Lamda expressions examples and "How to" section in quering and performance related topics.

Hope my brief list can help!

GibboK
  • 71,848
  • 143
  • 435
  • 658
1

This is of course not 'the most hardest' but just something to add to the list :

ThenBy() extension method

Without looking at its implementation I'm initially puzzled as to how it works. Everyone understands just fine how comma separated sort fields work in SQL - but on face value I'm skeptical that ThenBy is going to do what I really want it to do. How can it 'know' what the previous sort field was - it seems like it ought to.

I'm off to research it now...

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • 4
    The trick is that ThenBy is an extension method on IOrderedEnumerable (or IOrderedQueryable) rather than just IEnumerable/IQueryable. You can download my (very naive!) implementation from my talks page: http://csharpindepth.com/Talks.aspx - see "LINQ to Objects in 60 minutes" – Jon Skeet Mar 06 '09 at 07:10
0

The fact that you can't chain IQueryable because they are method calls (while still nothing else but SQL translateable!) and that it is almost impossible to work around it is mindboggling and creates a huge violation of DRY. I need my IQueryable's for ad-hoc in which I don't have compiled queries (I only have compiled queries for the heavy scenarios), but in compiled queries I can't use them and instead need to write regular query syntax again. Now I'm doing the same subqueries in 2 places, need to remember to update both if something changes, and so forth. A nightmare.

-1

Something i bet almost on one knows: you can use inline ifs in a linq query. Something like this:

var result = from foo in bars where (
    ((foo.baz != null) ? foo.baz : false) &&
    foo.blah == "this")
    select foo;

I would suppose you can insert lambdas as well although i haven't tried.

RCIX
  • 38,647
  • 50
  • 150
  • 207
  • 2
    That's just a conditional expression - why *wouldn't* you be able to use that? – Jon Skeet Jun 19 '09 at 07:23
  • I was of the (probably mistaken) impression that that is like a regular if: you wouldn't see any imbedding of regular ifs like that now would you? or i could be wrong... – RCIX Jun 19 '09 at 09:34
  • 3
    If is a statement and the conditional operator is an expression. They are different forms of the same concept of branching. In this case, though, you could do "foo.baz ?? false" and use the null coalescing operator :-) – Bryan Watts Jul 30 '09 at 03:22
  • I think more people know the ternary operator than the opposite.. – devoured elysium Jan 04 '10 at 18:46
  • Conditional expressions resulting in boolean values can be reduced to boolean or/and expressions, so `(foo.baz != null) ? foo.baz : false` is equivalent to `(foo.baz != null) && foo.baz`. I think this can be applied to any ternary expression that could be passed as a `where` condition. So that's not all that surprising, IMHO – Justin Morgan - On strike Feb 04 '11 at 16:44