Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. LINQ "let"

LINQ "let"

Scheduled Pinned Locked Moved The Lounge
36 Posts 16 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Marc Clifton
    wrote on last edited by
    #1

    Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

    Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

    P J R K Sander RosselS 9 Replies Last reply
    0
    • M Marc Clifton

      Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

      Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

      J Offline
      J Offline
      Jacquers
      wrote on last edited by
      #2

      Cool! I didn't know about it either. Now to find a use for it, just because :)

      1 Reply Last reply
      0
      • M Marc Clifton

        Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

        Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

        P Offline
        P Offline
        Pete OHanlon
        wrote on last edited by
        #3

        It's a useful tool in your arsenal. So how have you been solving this in the past? Multiple queries chained together? Just wait until you start using "into[^]".

        This space for rent

        M 1 Reply Last reply
        0
        • M Marc Clifton

          Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

          Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

          R Offline
          R Offline
          Rob Philpott
          wrote on last edited by
          #4

          I didn't know that and will probably forget quite soon too. Do people use that sort of syntax still? I never see it, and don't know what its called. My inclination would be something hideous like this:

          var a = strings.SelectMany(x => x.Split(' ')).Select(x => x.ToLower()).Where(x => x[0] == 'a' || x[0] == 'e' || x[0] == 'i' || x[0] == 'o' || x[0] == 'u');

          ...which I would call Linq, but may not be, or might be just some perverse form of it.

          Regards, Rob Philpott.

          R 1 Reply Last reply
          0
          • R Rob Philpott

            I didn't know that and will probably forget quite soon too. Do people use that sort of syntax still? I never see it, and don't know what its called. My inclination would be something hideous like this:

            var a = strings.SelectMany(x => x.Split(' ')).Select(x => x.ToLower()).Where(x => x[0] == 'a' || x[0] == 'e' || x[0] == 'i' || x[0] == 'o' || x[0] == 'u');

            ...which I would call Linq, but may not be, or might be just some perverse form of it.

            Regards, Rob Philpott.

            R Offline
            R Offline
            Richard Deeming
            wrote on last edited by
            #5

            That's the method chaining syntax. The other version is the query syntax. Query Syntax and Method Syntax in LINQ (C#)[^] I tend to prefer the method chaining syntax for most queries, but for certain queries, the query syntax looks cleaner.


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            OriginalGriffO 1 Reply Last reply
            0
            • R Richard Deeming

              That's the method chaining syntax. The other version is the query syntax. Query Syntax and Method Syntax in LINQ (C#)[^] I tend to prefer the method chaining syntax for most queries, but for certain queries, the query syntax looks cleaner.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #6

              I can't get my head round the Linq syntax, so I always use method chaining. I think it's the way the query is backwards (just like SQL) where method chaining fits C# syntax better (in my mind anyway).

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              R 9 M N 4 Replies Last reply
              0
              • M Marc Clifton

                Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

                Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                K Offline
                K Offline
                Kenneth Haugland
                wrote on last edited by
                #7

                Ah, you might like the LINQ to objects book[^] then, it is brilliant. (At least I think it is :) ) Tons of useful tips in it, and a very nice read as well.

                1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  I can't get my head round the Linq syntax, so I always use method chaining. I think it's the way the query is backwards (just like SQL) where method chaining fits C# syntax better (in my mind anyway).

                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

                  R Offline
                  R Offline
                  Rob Philpott
                  wrote on last edited by
                  #8

                  Agreed. So my next question would be: Is there anything you can do in one syntax that you can't in the other? Personally, if it takes more than a moment to figure out what it's trying to do, I revert to pre-2007 methods.

                  Regards, Rob Philpott.

                  R M 2 Replies Last reply
                  0
                  • R Rob Philpott

                    Agreed. So my next question would be: Is there anything you can do in one syntax that you can't in the other? Personally, if it takes more than a moment to figure out what it's trying to do, I revert to pre-2007 methods.

                    Regards, Rob Philpott.

                    R Offline
                    R Offline
                    Richard Deeming
                    wrote on last edited by
                    #9

                    Query syntax is rewritten by the compiler to the same series of method calls as the method chaining syntax, so there's nothing you can do in QS that you can't do in MCS. There are a few things that look a bit neater in QS - let being a prime example - but there's always a way to write the same query in MCS. There are quite a few extension methods that don't have an equivalent query keyword, so there are things you can do in MCS that you can't do in QS. LINQPad[^] is probably the best tool to compare the two syntaxes.


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    R 1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      I can't get my head round the Linq syntax, so I always use method chaining. I think it's the way the query is backwards (just like SQL) where method chaining fits C# syntax better (in my mind anyway).

                      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

                      9 Offline
                      9 Offline
                      9082365
                      wrote on last edited by
                      #10

                      You're not missing anything. I trialled Linq functions extensively a couple of years back and they were always slower (sometimes markedly so) than the traditional methods they 'replace'. It all looks very fancy and sophisticated but it's totally inefficient.

                      I am not a number. I am a ... no, wait!

                      Sander RosselS J 2 Replies Last reply
                      0
                      • M Marc Clifton

                        Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

                        Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                        Sander RosselS Offline
                        Sander RosselS Offline
                        Sander Rossel
                        wrote on last edited by
                        #11

                        Yeah, let is great. Sometimes I convert a query from method syntax to query syntax just so I can use let :)

                        Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

                        Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

                        Regards, Sander

                        1 Reply Last reply
                        0
                        • 9 9082365

                          You're not missing anything. I trialled Linq functions extensively a couple of years back and they were always slower (sometimes markedly so) than the traditional methods they 'replace'. It all looks very fancy and sophisticated but it's totally inefficient.

                          I am not a number. I am a ... no, wait!

                          Sander RosselS Offline
                          Sander RosselS Offline
                          Sander Rossel
                          wrote on last edited by
                          #12

                          You're missing out on a lot! LINQ can be a bit slower, but it's awesome for many use cases. When you really need the milliseconds go for regular ADO.NET, but how often do you really need that? My experience with LINQ is not that it's slow to use, but that people suddenly forget that their LINQ expression becomes a SQL query and start writing the most horrible, non-indexed queries, now THAT is a performance killer. What I really like about LINQ is that you can create your own extension methods and use those to create queries that read like regular sentences, or just a lot better than SQL in general (I mean, who remembers why all those WHERE clauses are there?) :)

                          Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

                          Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

                          Regards, Sander

                          N 1 Reply Last reply
                          0
                          • R Richard Deeming

                            Query syntax is rewritten by the compiler to the same series of method calls as the method chaining syntax, so there's nothing you can do in QS that you can't do in MCS. There are a few things that look a bit neater in QS - let being a prime example - but there's always a way to write the same query in MCS. There are quite a few extension methods that don't have an equivalent query keyword, so there are things you can do in MCS that you can't do in QS. LINQPad[^] is probably the best tool to compare the two syntaxes.


                            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                            R Offline
                            R Offline
                            Rob Philpott
                            wrote on last edited by
                            #13

                            Splendid, thanks for the info.

                            Regards, Rob Philpott.

                            1 Reply Last reply
                            0
                            • P Pete OHanlon

                              It's a useful tool in your arsenal. So how have you been solving this in the past? Multiple queries chained together? Just wait until you start using "into[^]".

                              This space for rent

                              M Offline
                              M Offline
                              Marc Clifton
                              wrote on last edited by
                              #14

                              Pete O'Hanlon wrote:

                              So how have you been solving this in the past? Multiple queries chained together?

                              My Linq tends to be rather simple. :)

                              Pete O'Hanlon wrote:

                              Just wait until you start using "into[^]".

                              Though for reporting, yup, been there, done that:

                              var categoryRanks = (from gs in geekSkills
                              where (gs.ProfileId == profile.Id)
                              join s in skills on gs.SkillId equals s.Id
                              select new { Level = gs.Level, CategoryId = s.CategoryId } into gss
                              join c in categories on gss.CategoryId equals c.Id
                              select new { Level = gss.Level, Name = c.Name } into gssc
                              group gssc by new { gssc.Name, gssc.Level } into g
                              select new SkillLevelBySkillByCategory() {
                              SkillLevel = g.Key.Level,
                              SkillLevelCount = g.Count(x => x.Level == g.Key.Level),
                              Name = g.Key.Name });

                              Marc

                              Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                              J 1 Reply Last reply
                              0
                              • OriginalGriffO OriginalGriff

                                I can't get my head round the Linq syntax, so I always use method chaining. I think it's the way the query is backwards (just like SQL) where method chaining fits C# syntax better (in my mind anyway).

                                Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

                                M Offline
                                M Offline
                                Marc Clifton
                                wrote on last edited by
                                #15

                                OriginalGriff wrote:

                                I can't get my head round the Linq syntax, so I always use method chaining.

                                I tend to use both, depending on what I'm doing. For example, this:

                                var categoryRanks = (from gs in geekSkills
                                where (gs.ProfileId == profile.Id)
                                join s in skills on gs.SkillId equals s.Id
                                select new { Level = gs.Level, CategoryId = s.CategoryId } into gss
                                join c in categories on gss.CategoryId equals c.Id
                                select new { Level = gss.Level, Name = c.Name } into gssc
                                group gssc by new { gssc.Name, gssc.Level } into g
                                select new SkillLevelBySkillByCategory() {
                                SkillLevel = g.Key.Level,
                                SkillLevelCount = g.Count(x => x.Level == g.Key.Level),
                                Name = g.Key.Name });

                                seems more readable to me than method chaining, but I also do things like this:

                                T record = mappedRecords[typeof(T)].Cast().Where(r => r.Row == row).Single();

                                because here, it flows better. Marc Marc

                                Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                1 Reply Last reply
                                0
                                • R Rob Philpott

                                  Agreed. So my next question would be: Is there anything you can do in one syntax that you can't in the other? Personally, if it takes more than a moment to figure out what it's trying to do, I revert to pre-2007 methods.

                                  Regards, Rob Philpott.

                                  M Offline
                                  M Offline
                                  Marc Clifton
                                  wrote on last edited by
                                  #16

                                  Rob Philpott wrote:

                                  Is there anything you can do in one syntax that you can't in the other?

                                  Possibly Cast<T> For example:

                                  T record = mappedRecords[typeof(T)].Cast().Where(r => r.Row == row).Single();

                                  But I'm not sure, I haven't seen any examples using query syntax. I suppose the point though is, you should cast before you query. :rolleyes: Marc

                                  Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                  R 1 Reply Last reply
                                  0
                                  • M Marc Clifton

                                    Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

                                    Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                    B Offline
                                    B Offline
                                    BillWoodruff
                                    wrote on last edited by
                                    #17

                                    Hi Marc, I first became aware of the 'Let and 'Into Linq operators through this 2011 CP article (which I down-voted for "lack of original content"): [^]. I have never used them :) because I have never invested the energy to learn to use the "fuller" query syntax (my bad). Your comment makes me wonder what I am missing (other than motivation). cheers, Bill p.s. the Microsoft example of 'Let you cite imho goes to a lot trouble do this:

                                    string[] strings =
                                    {
                                    "A penny saved is a penny earned.",
                                    "The early bird catches the worm.",
                                    "The pen is mightier than the sword."
                                    };

                                    string vowels = "aeiou";

                                    List<string> vowelstartwords = String.Join(" ", strings)
                                    .Split(' ')
                                    .Distinct()
                                    .Where(word => vowels.Contains(Char.ToLower(word[0])))
                                    .ToList();

                                    That example, taken as a programming challenge, interests me: it leaves me wondering if it could be significantly improved in terms of memory use and execution time, and if the Linq code using 'Let would, in fact, improve those usage parameters.

                                    «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

                                    R 1 Reply Last reply
                                    0
                                    • M Marc Clifton

                                      Rob Philpott wrote:

                                      Is there anything you can do in one syntax that you can't in the other?

                                      Possibly Cast<T> For example:

                                      T record = mappedRecords[typeof(T)].Cast().Where(r => r.Row == row).Single();

                                      But I'm not sure, I haven't seen any examples using query syntax. I suppose the point though is, you should cast before you query. :rolleyes: Marc

                                      Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                      R Offline
                                      R Offline
                                      Richard Deeming
                                      wrote on last edited by
                                      #18

                                      The Cast<T> part isn't a problem for query syntax - you just declare the type on the variable in the from clause:

                                      from T mappedRecord in mappedRecord[typeof(T)]
                                      ...

                                      But there's no query syntax keyword for Single, so you still have to call that as a method:

                                      T record = (from T mappedRecord in mappedRecords[typeof(T)]
                                      where mappedRecord.Row == row
                                      select mappedRecord).Single();

                                      I think the method chaining syntax is much cleaner - especially if you use the overload of Single to eliminate the Where call:

                                      T record = mappedRecords[typeof(T)].Cast<T>().Single(r => r.Row == row);


                                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                      1 Reply Last reply
                                      0
                                      • B BillWoodruff

                                        Hi Marc, I first became aware of the 'Let and 'Into Linq operators through this 2011 CP article (which I down-voted for "lack of original content"): [^]. I have never used them :) because I have never invested the energy to learn to use the "fuller" query syntax (my bad). Your comment makes me wonder what I am missing (other than motivation). cheers, Bill p.s. the Microsoft example of 'Let you cite imho goes to a lot trouble do this:

                                        string[] strings =
                                        {
                                        "A penny saved is a penny earned.",
                                        "The early bird catches the worm.",
                                        "The pen is mightier than the sword."
                                        };

                                        string vowels = "aeiou";

                                        List<string> vowelstartwords = String.Join(" ", strings)
                                        .Split(' ')
                                        .Distinct()
                                        .Where(word => vowels.Contains(Char.ToLower(word[0])))
                                        .ToList();

                                        That example, taken as a programming challenge, interests me: it leaves me wondering if it could be significantly improved in terms of memory use and execution time, and if the Linq code using 'Let would, in fact, improve those usage parameters.

                                        «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

                                        R Offline
                                        R Offline
                                        Richard Deeming
                                        wrote on last edited by
                                        #19

                                        I'd be inclined to avoid joining the strings just to split them again. I'd also be inclined to use an array of char, rather than searching a string - although I doubt it would make much difference. You've also added a Distinct and a ToList which weren't in the original example. :)

                                        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

                                        IEnumerable<string> vowelStartWords = strings
                                        .SelectMany(sentence => sentence.Split(' '))
                                        .Where(word => Array.IndexOf(vowels, char.ToLower(word[0])) != -1)
                                        ;


                                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                        B M 2 Replies Last reply
                                        0
                                        • M Marc Clifton

                                          Learned something new today. I was googling for CRC algorithms and came across this nifty site[^] and started perusing it more generally, then realized I had no idea about let clauses in query expressions![^] Geez, I've been using LINQ for a while now, and didn't know about that. :doh: Marc

                                          Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                          N Offline
                                          N Offline
                                          Nish Nishant
                                          wrote on last edited by
                                          #20

                                          Marc, you probably know this by now, but let is just syntactic sugar for the Select method.

                                          Regards, Nish


                                          Website: www.voidnish.com Blog: voidnish.wordpress.com

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups