convert this LINQ expression into Lambda

35,818

Solution 1

To convert a Linq query to it's Lambda equivalent:

  1. Download Linqpad and run your query.
  2. In the results window, click on the "λ" button in the toolbar. It's right above the Results window
  3. Your query will be converted to a Lambda expression equivalent!

enter image description here

Solution 2

You can take a look at 101 LINQ Samples and C# 3.0 QUERY EXPRESSION TRANSLATION CHEAT SHEET

Solution 3

Here's the heuristic that I follow:

Favor LINQ expressions over lambdas when you have joins.

I think that lambdas with joins look messy and are difficult to read.

Solution 4

I usually use ReSharper to help me convert things to method chains and lambda's, which helps me go back and forth fairly easy.

    var result = from g in grocery
                 join f in fruit on g.fruitId equals f.fruitId into tempFruit
                 join v in veggie on g.vegid equals v.vegid into tempVegg
                 from joinedFruit in tempFruit.DefaultIfEmpty()
                 from joinedVegg in tempVegg.DefaultIfEmpty()
                 select new { g.fruitId, g.vegid, fname = ((joinedFruit == null) ? string.Empty : joinedFruit.fname), vname = ((joinedVegg == null) ? string.Empty : joinedVegg.vname) };

And then using ReSharper's option of convert LINQ to method chain equals the following:

        var result =grocery .GroupJoin(fruit, g => g.fruitId, f => f.fruitId, (g, tempFruit) => new {g, tempFruit})
                            .GroupJoin(veggie, @t => @t.g.vegid, v => v.vegid, (@t, tempVegg) => new {@t, tempVegg})
                            .SelectMany(@t => @[email protected](), (@t, joinedFruit) => new {@t, joinedFruit})
                            .SelectMany(@t => @[email protected](),(@t, joinedVegg) =>
                                new
                                    {
                                        @t.@[email protected],
                                        @t.@[email protected],
                                        fname = ((@t.joinedFruit == null) ? string.Empty : @t.joinedFruit.fname),
                                        vname = ((joinedVegg == null) ? string.Empty : joinedVegg.vname)
                                    });

Granted the output is less then desirable, but It at least helps in starting somewhere on understanding the syntax.

Solution 5

Here’s how you might write this query in lambda:

var cus­tomers = new List {
new Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer1” },
new Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer2” },
};

var user­Cus­tomers = new List {
new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer1”, User = “not-admin” },
new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer1”, User = “admin” },
new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer2”, User = “not-admin” },
new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer2”, User = “admin” },
new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer1”, User = “not-admin”     },
new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer1”, User = “admin” },
new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer2”, User = “not-admin” },
new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer2”, User = “admin” }
};

Using query expres­sion

var query =
from c in cus­tomers
join uc in user­Cus­tomers on
new { c.CompanyId, c.CustomerId } equals new { uc.CompanyId, uc.CustomerId }
where c.CompanyId == “AC” && uc.User == “admin“
select c;

Using lambda expres­sions

var lambda =  cus­tomers.Where(c => c.CompanyId == “AC”) // inner sequence
.Join(userCustomers.Where(uc => uc.User == “admin”), // outer sequence
c => new { c.CompanyId, c.CustomerId }, // inner key selec­tor
uc => new { uc.CompanyId, uc.CustomerId }, // outer key selec­tor
(c, uc) => c);

Both approach yields the same result (cus­tomer with com­pany Id “AC” and cus­tomer Id “Customer1”), but as you can see, lambda expres­sion is much harder to write and read!

Hope this helps!

Share:
35,818
RameshVel
Author by

RameshVel

தொட்டு விடும் தூரத்தில் வெற்றியும் இல்லை விட்டு விடும் எண்ணத்தில் நானும் இல்லை - ரமேஷ் வேல் building https://dailybasket.com/?utm_source=stackoverflow&utm_medium=stackoverflow&utm_campaign=stackoverflow_bio

Updated on July 20, 2020

Comments

  • RameshVel
    RameshVel almost 4 years

    Guys, I have a hard time converting this below linq expression(left join implementation) to lambda expression (for learning).

    var result = from g in grocery
           join f in fruit on g.fruitId equals f.fruitId into tempFruit
           join v in veggie on g.vegid equals v.vegid into tempVegg
           from joinedFruit in tempFruit.DefaultIfEmpty()
           from joinedVegg in tempVegg.DefaultIfEmpty()
           select new { g.fruitId, g.vegid, fname = ((joinedFruit == null) ? string.Empty :     joinedFruit.fname), vname = ((joinedVegg == null) ? string.Empty : joinedVegg.vname) };
    

    Can some one suggest me how to do this.

    And i really appreciate if someone give me the excellent tutorial links for "C# Lambdas & Linqs"

  • RameshVel
    RameshVel over 14 years
    thanks jim for the reply. But i wanted to do this in lambda to get familiar with.. i mentioned that already its for learning...
  • RameshVel
    RameshVel over 14 years
    thanks for the links Dzmitry... the cheat sheet is useful... i already have a look at 101 samples..
  • satyavrat
    satyavrat over 14 years
    i thought that was only the paid version that had loads of samples etc
  • Mitch Wheat
    Mitch Wheat over 14 years
    The free version comes with samples too.
  • RameshVel
    RameshVel over 14 years
    hey where would i get the source code for the 101 samples.. any idea.. i couldnt find there...
  • RameshVel
    RameshVel over 14 years
    thanks Mark for your response.. i will run it over here and will let you know if that works..
  • atconway
    atconway almost 11 years
    I have Linqpad but without creating a 'connection' to a service that I can query, I can not see the button for the lambda. I do not know how to just paste in a LINQ query and convert it to a lambda. Is this actually possible?
  • Brad Parks
    Brad Parks almost 11 years
    I just added a pic for where the button is in the UI. I don't have Linqpad on hand, but I think you need to have a runnable query there before it can be converted to a Lambda. In another post, I detailed how you can test data in Linqpad without needing a DB, here: stackoverflow.com/questions/4611031/…
  • Toolkit
    Toolkit over 5 years
    can it convert SQL to lambda or LINQ? Doesn't seem to be working
  • Brad Parks
    Brad Parks over 5 years
    I haven't used it in a long time, but what does clicking the SQL button beside the λ do?