Which one is better lambda expressions or

I have following LINQ to SQL query expression

from msg in TblUserMessages join user in Aspnet_Users on msg.FromUserID equals user.UserId select new { msg.FromUserID, msg.ToUserID, msg.MessageLocationID, msg.MessageID, user.UserName }

And following LINQ method expression:

TblUserMessages .Join ( Aspnet_Users, msg => msg.FromUserID, user => user.UserId, (msg, user) => new { FromUserID = msg.FromUserID, ToUserID = msg.ToUserID, MessageLocationID = msg.MessageLocationID, MessageID = msg.MessageID, UserName = user.UserName } )

Both of these return same result set. Which is e.g. :

82522f05-2650-466a-a430-72e6c9fb68b7 6b2a174a-8141-43d2-b3ad-5b199bcbfcae 1 1 waheed

Which one is better to use. The FIRST one or the SECOND one.


-------------Problems Reply------------

They are equivalent. They don't just return the same result set - they compile to the same code.

Use query expressions or dot notation for individual cases depending on readability. For joins, I find the dot notation quite cumbersome - but I use it for situations where I only have one or two clauses (usually where/select). Even with two clauses (usually where and select) I find dot notation nice if you then need to use it anyway. For example, I like:

var query = people.Where(person => person.Age > 18)
.Select(person => person.Name)


var query = (from person in people
where person.Age > 18
select person.Name)

For more complicated queries (e.g. joins) I'd probably just separate the two:

var baseQuery = from person in people
where person.Age > 18
join company on person.CompanyId equals company.CompanyId
select new { person.Name, company.Name };

var fullQuery = baseQuery.Skip(100)

I just find this separation makes it easier to read.

I believe it's really useful for developers to understand at least the basics of what query expressions do - the fact that they're basically translations into dot notation, and that the language itself doesn't know anything about LINQ to Objects, LINQ to SQL etc; it's just a case of following an appropriate pattern. It's a great bit of design, which means query expressions only affect one little bit of the language specification.

There's no better one. Use what you like. I would, in this case, go with the 'query' syntax, since I think it's more readable than the second one. Moreover, since we're writing SQL anyway, I think this syntax resembles it better. But I'm sure others will disagree and tend to choose the lamda version.

I usually go with the latter syntax btw, since I prefer the lambda syntax cause it is often more readable and shorter.

See also this SO question.

I'd always go for the more readable option and in this case I think its the LINQ snippet.

Both will perform equally well, but I will prefer the first since it's easier to read and understand.

Whichever you find easier to read.

"write your code, then measure it to find out what to refactor." Have you measured both? Better is subjective.

Are you finding a problem with either one that is making you want to choose one over the other?

There IS one little difference between the two types of syntax. The query expression one will take longer to compile because the compiler has to transform it into the dot syntax. Of course, it is almost completely immaterial because:

  1. the compilation overhed is minimal,
  2. the emitted IL that runtime needs to deal with is exactly the same for both cases.

I use Lambda Expressions when I have to build query dynamically, and LINQ to SQL when query is fully known.

IQueryable<IncomeDetailsEntity> query;
if (!string.IsNullOrEmpty(regioncode))
if (!string.IsNullOrEmpty(compcode))
query = db.IncomeDetailsEntities.Where(i => i.RegionCode == regioncode && i.CompanyCode == compcode);
query = db.IncomeDetailsEntities.Where(i => i.RegionCode == regioncode);
query = db.IncomeDetailsEntities;
return query.Select(i => new { i.RegionCode, i.Budget });

Category:c# Views:0 Time:2009-08-20

Related post

  • What is a good use of lambda expressions, and how can I learn to use them? 2008-08-24

    This question already has an answer here: C# Lambda expression, why should I use this? 12 answers I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make m

  • Recursive lambda expression to traverse a tree in C# 2008-09-14

    Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#. --------------Solutions------------- Ok, I found some free time finally. Here we go: class TreeNode { public string Value { get; set;} public List

  • Is there a case where delegate syntax is preferred over lambda expression for anonymous methods? 2008-09-19

    With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax. Any place where we still

  • Dynamic LINQ and Dynamic Lambda expressions? 2008-09-22

    What is the best way of dynamically writing LINQ queries and Lambda expressions? I am thinking of applications where the end user can design business logic rules, which then must be executed. I am sorry if this is a newbie question, but it would be g

  • C# Lambda Expressions or Delegates as a Properties or Arguments 2008-09-26

    I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime

  • C# Lambda expression, why should I use this? 2008-10-03

    I have quickly read the Microsoft Lambda Expression documentation. I see example that have help me to understand more like this one : delegate int del(int i); del myDelegate = x => x * x; int j = myDelegate(5); //j = 25 But, I still do not underst

  • What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)? 2008-10-16

    This question already has an answer here: delegate keyword vs. lambda notation 5 answers What is the difference between anonymous methods of C# 2.0 and lambda expressions of C# 3.0.? --------------Solutions------------- The MSDN page on anonymous met

  • Why is it bad to use an iteration variable in a lambda expression 2008-10-22

    I was just writing some quick code and noticed this complier error Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable. I

  • Lambda Expression Tree Parsing 2008-10-26

    Thanks in advance guys. I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand. if I pass in a lambda expression like: p => p.Title == "title" everything works. however if

  • Lambda Expressions in Delphi Prism/Oxygene 2008-11-06

    I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression to calculate a fibonacci number : var fib : Func<int32, int32>; fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n); fib(3); When I run t

  • How do I pronounce "=>" as used in lambda expressions in .Net 2008-11-07

    I very rarely meet any other programmers! My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense. So how do I say or read "=>" as in:- IEnumerable<

  • Lambda expression exercise 2008-11-13

    I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise... is there a way to simplify a c++ integration function like this: // Integral Function double integrate(double a, double b, double (*f)(double))

  • C# Syntax - Example of a Lambda Expression - ForEach() over Generic List 2008-12-04

    First, I know there are methods off of the generic List<> class already in the framework do iterate over the List<>. But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a List<>, an

  • How do you do an IN or CONTAINS in LINQ using LAMBDA expressions? 2008-12-09

    I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling. SELECT * FROM Project WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155') Any help would be

  • Why must a lambda expression be cast when supplied as a plain Delegate parameter 2009-01-04

    Take the method System.Windows.Forms.Control.Invoke(Delegate method) Why does this give a compile time error: string str = "woop"; Invoke(() => this.Text = str); // Error: Cannot convert lambda expression to type 'System.Delegate' // because it is

  • How do I invoke a method through reflection with a lambda expression as a parameter? 2009-01-12

    I want to do this: MethodInfo m = myList.GetType().GetMethod("ConvertAll", System.Reflection.BindingFlags.InvokeMethod).MakeGenericMethod(typeof(object)); List<object> myConvertedList = (List<object>)m.Invoke(myList, new object[]{ (t =

  • EventHandlers and Anonymous Delegates / Lambda Expressions 2009-01-13

    I'm hoping to clear some things up with anonymous delegates and lambda expressions being used to create a method for event handlers in C#; for myself at least. Suppose we have an event that adds either an anonymous delegate or lambda expression [for

  • Is it possible to cast a delegate instance into a Lambda expression? 2009-01-21

    Here the context for my question: A common technique is to declare the parameter of a method as a Lambda expression rather than a delegate. This is so that the method can examine the expression to do interesting things like find out the names of meth

  • Lambda expressions support in VS2008 SP1 2009-01-23

    Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something? #include <algorithm> #include <iostream> #include <ostream>

  • Lambda Expression cause weakreference's target cannot be GC? 2009-02-11

    namespace Test { class Test { delegate void HandleMessage(string message); public void handleMessage(string message){} static void Main(string[] args) { HandleMessage listener1 = new Test().handleMessage; WeakReference w1 = new WeakReference(listener

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.116 (s). 11 q(s)