Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything that is possible in LINQ but not Lambda?

Tags:

.net

lambda

linq

I am thinking about code standards for a .net project (c sharp language) and I personally really like using lambda expressions in the various extension methods on IEnumerable etc (Where, GroupBy, blah, blah) and don't really like the LINQ syntax.

I know it is a personal preference thing, so I am not asking which is best, but for me and my team we tend to find the lambda approach to be more easily readable. So I am thinking of saying in our coding standards to always use the Lambda approach but I got to thinking...

Is there anything that can only be achieved using LINQ syntax? By something I mean that you could build a particular expression tree using LINQ that you simply could not using the extension methods with lambda expressions. I am thinking that the answer is no as tools like resharper and linqpad are able to convert between them and I have been able to work out everything I have ever needed in lambda but I wonder if there is an edge case somewhere that the smart people on here know about?

like image 493
kmp Avatar asked Feb 22 '23 01:02

kmp


2 Answers

"Possible" and "convenient" are different ;p Everything is possible; LINQ syntax ultimately compiles to lambda syntax, and there are things possible with extension syntax that aren't possible in LINQ syntax (Distinct() in C#, for example, although it exists in VB.NET LINQ).

However! When you have lots of variables in a LINQ query, that is a pain to map, as you would need lots of additional projections to intermediate objects (probably anonymous types); for example, try writing (in lambda syntax):

var query = from x in xSource
            from y in x.SomeCollection
            from z in zSource
            let foo = x.Foo + z.SomeMethod()
            order by foo
            select new {x,y,z,foo};

it is possible, but frankly a PITA.

like image 175
Marc Gravell Avatar answered Jun 06 '23 10:06

Marc Gravell


The expression syntax (from x in something ..) is converted by the compiler to the extension method syntax. And you can do more with the extension methods than in the expression syntax (although the latter might sometimes be simpler).

like image 31
Hans Kesting Avatar answered Jun 06 '23 08:06

Hans Kesting