3

I see this all over the web, however I'm curious if there isn't an easier way to write this in lambda?

  var x = from c in db.Client
    from p in db.Prospects
    from ct in db.Countys
    select new ViewModelExcelReport 
    {
         client = c.ClientName,
         cntyCounty = ct.County,
         sctSection = p.Section
    };

I would like to see a lambda expression that does NOT use joins, as though i am almost certain that i have seen one without the joins, but if this isn't possible ofcouse i'd like to see one with, thanks.

1
  • well, are Prospects and Countys related in some way? By the way, shouldn't that be Counties? If there is no relationship, whats wrong with your current statement? If there is a relationship how are we supposed to know? Commented Nov 26, 2013 at 17:35

1 Answer 1

5

Basically multiple from clauses contribute SelectMany calls. So your code is something like:

var x = db.Client
          .SelectMany(c => db.Prospects, (c, p) => new { c, p })
          .SelectMany(z => db.Countys, (z, ct) => new { z, ct })
          .Select(zz => new ViewModelExcelReport 
                        {
                            client = zz.z.c.ClientName,
                            cntyCounty = zz.ct.County,
                            sctSection = zz.z.p.Section
                        });

Note how this is rather more longwinded than the query expression - the compiler takes care of keeping track of all the range variables via transparent identifiers. Why do you want this in lambda form? What do you see as being the benefit? The query expression will be translated into exactly the same code, so you should use whichever one is clearer - which in this case looks like the query expression, IMO.

As an aside, I'd strongly recommend that you change your property names (in ViewModelExcelReport) to more idiomatic ones if you possibly can.

Sign up to request clarification or add additional context in comments.

3 Comments

I used some old code as reference ( the reason for some stupid names), thanks for the notes as well. As for me wanting this in lambda,..., everything else in my code is lambda therefore i was attempting to stick with everything being the same (lambda ) however its not easier and i will be using the query expression. Thanks again
@Pakk: It's definitely worth being comfortable with both forms. There's no benefit in sticking rigidly to one or the other - if other folks on the team are only happy with one form, get them to learn ;)
@Pakk let can be very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.