LINQ + Lambda expressions - C# tutorial

Поделиться
HTML-код
  • Опубликовано: 18 июл 2021
  • Lambda expressions can reduce your code, make it more readable and turn you into a more efficient programmer. I'll give you the rundown on what lambda is, how it's built and show you a bunch of useful lambda functions. Lastly I'll show you how to create your own lambda functions.
    Give the video a like if you enjoyed it! Also, come join the discord: / discord
    ❤️ Become a Tarobro on Patreon: / tarodev
    =========
    🔔 SUBSCRIBE: bit.ly/3eqG1Z6
    🗨️ DISCORD: / discord
    ✅ MORE TUTORIALS: / tarodev

Комментарии • 197

  • @jacobs.7925
    @jacobs.7925 Год назад +102

    My only wish is that this video was 35 minutes long with 20+ examples instead. So great!!
    Thanks a ton!!

    • @DannyBoy443
      @DannyBoy443 Год назад +1

      Yeah he and I have talked about the speed of the videos too. I'm not a beginner to C#, but I'm not a pro yet either.

  • @raoulbest5395
    @raoulbest5395 3 года назад +21

    This is extremly helpful. I've known a bit about lambda functions before but making one actually blew my head off.

    • @Tarodev
      @Tarodev  3 года назад +7

      They truly are amazing. I rarely find myself writing loops nowadays... In both game dev and my professional day job.

  • @Worlnof
    @Worlnof Год назад +7

    That Cyberpunk joke cracked me xD

  • @SlimeWithClass
    @SlimeWithClass 3 года назад +90

    This tutorial was perfect, I really like how you compared lambdas to a more simplistic loop. It helped it click in my head

    • @Tarodev
      @Tarodev  3 года назад +9

      I was hoping it would serve that purpose! 😊

    • @koferperk
      @koferperk 2 года назад

      i agree

    • @CyCloNeReactorCore
      @CyCloNeReactorCore 2 года назад +1

      Except, this is really the exact opposite of what you were intended to get from the video. The lambda is not the loop. LINQ is running the loop based off of the condition from the lambda expression, to my understanding. Although, I'm nowhere near tarodevs level of knowledge, and I could just straight up be wrong lol.

    • @justiceokechukwu7728
      @justiceokechukwu7728 Год назад

      @@CyCloNeReactorCore You're right mate

  • @THVLPLYR
    @THVLPLYR Год назад +2

    the intro has this vibe i cannot explain....

  • @faremir
    @faremir 2 года назад +41

    There's also the thing about performance. Althought in many case LINQ is fasterish and less bug prone than manual foreach ( things like .Except() and especially parallel aggregation), most of the time LINQ will be slower, because of the overhead of delegate invocation. And not even speaking about for loop which is way faster then foreach.
    So if you actually need to care about performance for example rendering, real time data analysis, etc. it's good to be aware and benchamarking of test subset won't ever harm you.

    • @matthewiskra771
      @matthewiskra771 2 года назад +2

      And as an Olde Timey Programmer (kids... I did key-to-tape! I read EBCDIC, UNICODE, and ASCII! Y'all don't know the pain of dropping yer deck and doing a floor sort! Git off my iLawn before I sic my eDog on ya!):
      Always design and code for performance from day one if you ever expect to have high performing code.
      That being said, this is cool, and better yet, useful.

    • @LuukDomhof
      @LuukDomhof 2 года назад

      There are MANY cases where a foreach loop is faster than a for loop. Check some benchmarks ;)

    • @faremir
      @faremir 2 года назад

      @@LuukDomhof In any case my previous comment was specifically targeting LINQ.
      Either way... I agree there are cases (even tho highly specific) where foreach is slightly more efficient than for loop. And even with Ben Watson's great article back in 2014 (.NET loop performance) there is no general rule. That's why I suggested that people should make their own tests and know what their code is doing.

  • @samadhistate9637
    @samadhistate9637 2 года назад +2

    You break things down and explain it really well. Also your voice is clear, calm and not rushed. And no stupid drawn-out intros. Thanks for posting - will watch more of your tutorials.

  • @_acea4171
    @_acea4171 2 года назад +3

    THANK YOU SO MUCH. I've been looking everywhere for a tutorial which really deconstructed lambda expressions, but couldn't find one anywhere. You are a lifesaver.

  • @kdeger
    @kdeger 3 года назад +107

    As a fellow game developer, I humbly suggest your tutorials to my team, especially the simplicity and real world samples are just on point. Keep up the good work and thank you for sharing👍

    • @Tarodev
      @Tarodev  3 года назад +12

      That comment made my night mate. Thank you!

    • @Tarodev
      @Tarodev  3 года назад +18

      They'll sit down to the intro of the video and think what the hell is this

  • @windup247
    @windup247 Год назад +2

    You could honestly teach teachers how to teach. You're that good.

  • @bernardodelcast
    @bernardodelcast 2 года назад +2

    I have struggled with lambdas A LOT (I think mainly because most examples of it that I had seen were so abstract and high level), but this has been probably the best explanation of them yet.
    Thanks!

  • @activate9741
    @activate9741 2 года назад +4

    This actually was so simple but helped so much, I hope you can do a “C# tutorial series” or something along that line! Keep up the good work man

  • @AyItsKevin
    @AyItsKevin 2 года назад +3

    Love the threatening aura intro then complete coddling immediately after 🤣 needs to be in more vids

    • @Tarodev
      @Tarodev  2 года назад +2

      K & d in the wild

    • @Tarodev
      @Tarodev  2 года назад +1

      K & d in the wild

  • @eerongal
    @eerongal 2 года назад +61

    While i agree that lambda's are awesome, what you're mostly focusing on here is LINQ, and NOT LAMBDA's (though you are using lambda's with linq, which isnt not really required). The select/where/orderby/etc are all LINQ functions. The "n => n>5" is the lambda part. Everything else is LINQ. Lambda's have FAAAAR more uses than just LINQ. And LINQ can be used without lambda's.

    • @Tarodev
      @Tarodev  2 года назад +12

      To be fair, I call the arrow function a lambda operator and make sure there's lambda in every example. I debated including the distinction between the two and decided against it. It's an inner battle deciding what to include and cull from each tutorial and there's usually more thought that goes into it than what most people think.
      For example, would it confuse people unnecessarily while they're trying to process a concept? Re-read your comment and tell me (although written well) it wouldn't be confusing for a brand new dev.

    • @CyCloNeReactorCore
      @CyCloNeReactorCore 2 года назад +8

      ​@@Tarodev As a fairly new dev, watching your video, I understood the lambda to be the method chaining, and the lambda expression within the parenthesis was also called lambda. This led to alot of confusion when I found out that wasn't the case. IE "why does his lambda look nothing like mine?" in reference to the LINQ aspect. Rather than "Lambda (+LINQ)" it really just feels like "LINQ (+Lambda)"
      That being said, this video was very helpful, and did lead me into a grasp on Lambda expressions and statements, so the video itself wasn't bad at all, I would just say to re write the title, so it isn't as misleading.

    • @Tarodev
      @Tarodev  2 года назад +6

      @@CyCloNeReactorCore Yup, rewatching it I did a poor job of distinguishing them (or even mentioning it >

    • @RayanMADAO
      @RayanMADAO Год назад +3

      @@Tarodev It's okay!! Not every video can address every single facet of the subject. You helped me understand lambdas more so thank you.

    • @daruma5018
      @daruma5018 Год назад +1

      @@Tarodev "If I Had More Time, I Would Have Written a Shorter Letter" - Blaise Pascal

  • @gregorydeclercq2990
    @gregorydeclercq2990 Год назад +2

    The world of lambda expressions seemed so harsh and difficult, until I saw your video. Thanks for the simplicity 🙏

  • @mikelambert5426
    @mikelambert5426 2 года назад +2

    Hey man, i have to say it, your explanation was crystal clear. It was as relaxing (no noisy music and what's up boyz) as it was helpful. Thank you.

    • @Tarodev
      @Tarodev  2 года назад

      This was the first thing I read after waking up. Thanks mate, glad you enjoyed it.

    • @Tarodev
      @Tarodev  2 года назад

      Although it still has a pretty stupid intro 😜

  • @paulkohler8868
    @paulkohler8868 2 года назад

    I enjoy your videos. Though I've been using and making lambda functions for some time, seeing them this way taught me something new.

  • @reggieisnotadog4841
    @reggieisnotadog4841 9 месяцев назад +1

    I have never understood lambda functions before and you just made it so easy. Thank you so much for this video, even if I do feel a bit sick at all the time I wasted writing loops that I didn't have to write.

    • @Tarodev
      @Tarodev  9 месяцев назад +1

      Just don't use them in update 😊

  • @jnicoulakos
    @jnicoulakos 2 года назад +1

    I like this video because you encourage people to look into other options. :) Keep up the good work!

  • @Icey0812
    @Icey0812 2 года назад +4

    Great video! Really glad to see tutorials that cover more advanced topics for beginners.
    I do find this tutorial covers a lot of System.Linq, which might cause beginners to mix that up with lambda expressions. Lambda expressions is simply a short hand to create an anonymous function. I think it might be beneficial to cover the following:
    - Differences between anonymous functions and Linq/Extension methods.
    - Other usage of anonymous functions (i.e. assigning a function to a variable/parameters, callback using System.Action)

    • @CyCloNeReactorCore
      @CyCloNeReactorCore 2 года назад

      Exactly! This is what happened to me for a brief while when i first watched this video.. Great video though!

  • @IvarDaigon
    @IvarDaigon 2 года назад +5

    there is a downside to using LINQ lambdas instead of for each and that is you can't step through the code that is being iterated upon, so while it may be simpler to write, you are actually making the code much harder to debug.
    This is fine if the code is simple and will not throw any exceptions but as soon as the code becomes complex and is likely to throw exceptions while iterating through the list then you'll have a really hard time debugging it..
    An example of this is using LINQ to initialize a list of objects from a set of records that come from a database.
    Lets say there is a conversion error when attempting to convert one of the values from the DB into the datatype of the object property you are trying to set. Using LINQ you have no easy way of knowing which item in the list failed.
    So yeah lambas are great until there is a problem that can only be debugged by stepping through code.

    • @Tarodev
      @Tarodev  2 года назад

      You're right. Writing actual loops also gives you more granular control, thus if done right, better performance. This is negligible for 99% of cases, but it should be known.
      Regarding your point, it helps having tooling which can convert lambdas into loops and back, such as the power hungry resharper. Side note: Sometimes I convert some nested loops into lambda using resharper and the resulting lambda gives me a brain haemorrhage.

    • @r1pfake521
      @r1pfake521 2 года назад +2

      Which editor are you using? With full Visual Studio (not sure about VS Code) you can debug lambdas and place breakpoint inside lambdas (important, the cursor must be inside the lambda before you add the breakpoint, otherwise it will be added at the wrong position) then you step through the code and debug it like a normal loop iteration, where you would place the breakpoint inside the loop code.

    • @Tarodev
      @Tarodev  2 года назад +2

      @@r1pfake521 I actually did not know this. Thanks for the tip!

  • @TheOriginalDarkGlitch
    @TheOriginalDarkGlitch 2 года назад +1

    RUclips has been recommending this video for literally half a week. I should have watched this sooner lol. Great video!

    • @Tarodev
      @Tarodev  2 года назад

      Sometimes they know, lol

  • @denisstasyuk6738
    @denisstasyuk6738 2 года назад +1

    Just to add to all comments above, your typing speed is outstanding😳

  • @blerd7068
    @blerd7068 2 года назад

    Understood within 2 minutes of the video. Great Job. I need to now practice. Thanks!

  • @jugibur2117
    @jugibur2117 2 года назад +2

    Wow, C# is really great, thanks for these infos

  • @Vykhari1
    @Vykhari1 Год назад +1

    Thank you very much. It's really helped me!!

  • @Notreal76
    @Notreal76 Год назад

    You are a great Teacher. Thank you

  • @castlecodersltd
    @castlecodersltd Год назад

    Great video. Always good to refresh your knowledge or learn new stuff

  • @omkargodse5726
    @omkargodse5726 8 месяцев назад

    Wonderful! So easy to understand!

  • @rambertoeco8930
    @rambertoeco8930 2 года назад

    Man, you never disappoint, thanks!

  • @goverdhanjayaram3683
    @goverdhanjayaram3683 7 месяцев назад

    Thank you very much ! Very useful video !

  • @Kukuthepooch
    @Kukuthepooch 2 года назад +1

    The cyberpunk joke won me over. Good job.

  • @kellybmackenzie
    @kellybmackenzie Год назад

    This is amazing, thank you so much!!

  • @fiscpar2305
    @fiscpar2305 Год назад

    Jacked and C# instructor? I am among my peeps!
    Thank you for your precious help!!

  • @synchaoz
    @synchaoz 2 года назад +1

    You sir, are a legend. Thank you for this.

  • @schmidtlach
    @schmidtlach 4 месяца назад

    👏👏👏Excellent explanation. Clear and to the point.

  • @lukamuller7305
    @lukamuller7305 Год назад +1

    Great Tutorial Thanks m8

  • @divandebruin5767
    @divandebruin5767 Год назад

    Thanks very much for this, subscribed long ago 🎉

  • @setpopa5357
    @setpopa5357 11 месяцев назад +1

    Man this was great just explained two advanced topics in 6 mins

  • @scevvin7788
    @scevvin7788 Год назад

    Love the golden ratio used in the list example

  • @erandafernando94
    @erandafernando94 2 года назад

    thanks fam! great video!

  • @abhisheksuper20
    @abhisheksuper20 Год назад

    Just purely amazing!!

  • @nested9301
    @nested9301 2 года назад +1

    I'm in love with c# wow

  • @torrvic1156
    @torrvic1156 10 месяцев назад

    That was rad dude!

  • @spirit5923
    @spirit5923 Год назад +1

    This stuff was so much fun to play with. Proceeded to write the dumbest code to make a string basically nonsensical and I couldn't be more proud of my work.

    • @Tarodev
      @Tarodev  Год назад +1

      I'm also proud of you

    • @spirit5923
      @spirit5923 Год назад

      @@Tarodev Thanks, papa!

  • @gustavo3220
    @gustavo3220 Год назад +1

    love your sense of humor

  • @shariel9731
    @shariel9731 2 года назад

    This was really helpful, great tutorial!

    • @Tarodev
      @Tarodev  2 года назад

      Thanks mate 🙏

  • @Ne1gh_
    @Ne1gh_ 5 месяцев назад

    the best tutorial i've ever seen

  • @NyteShade76
    @NyteShade76 2 года назад +3

    I don't think that Cyberpunk reference will ever get old, even if Unity updates their code 10 years from now :D

  • @luigidreemurr6034
    @luigidreemurr6034 Год назад

    That burn on cyber punk though. God damn!
    Very informative. I know how to use lamda but not really why it worked that way. Even picked up some new uses. Thank you for a great video!

  • @NotNazuh
    @NotNazuh 2 года назад +1

    Great explanation

  • @bquimby5223
    @bquimby5223 Год назад

    Whoa. Solid video

  • @gustavosalmeron2013
    @gustavosalmeron2013 Год назад +1

    Your videos are AWESOME! You are very didactic, patient and interesting, thank you so much!
    I've been trying to learn pure C# but whenever I ask questions to a "friend" of mine, he mocks me, says I should have known that already, that my code looks like shit.... You, on the other side, make the learning process productive and healthy. Thank you so much!

    • @DnkyWnky
      @DnkyWnky Год назад +4

      You should probably get a new friend

    • @torrvic1156
      @torrvic1156 10 месяцев назад +1

      He is abuser. You should define your borders in your relationship and tell him what you like and what not. Just talk with him about your feelings.

    • @gustavosalmeron2013
      @gustavosalmeron2013 10 месяцев назад

      @@torrvic1156 actually, I don't speak with him anymore. I blocked him and don't answer him, I don't even have contact. Never been happier!

  • @tonykamin3840
    @tonykamin3840 10 месяцев назад

    Nice tutorial, and bonus points for including Valheim in the list of Steam games (one of my all time favorites). 😀

  • @sudeepjainsudeep
    @sudeepjainsudeep 2 года назад +1

    Those have a C# background before moving to Unity like me are already using it extensively. During the course I have read on some blogs and Q&A forums that Unity might have performance difficulty while processing these expression. Some even said Foreach loops are bad. But so far I haven't observed any issues. Go for it, you can reduce your code by 30% and less time on maintenance.

  • @fredimachadonet
    @fredimachadonet 2 года назад +3

    Awesome! Thanks for your content!
    Not sure if someone already mentioned this before, but as soon as you use foreach in a lazy IEnumerable it will force the query execution. Not sure if that was the intention in your AddRatingToNames method.
    If you want to stay lazy you could do this instead of using the foreach:
    return games.Select(g =>
    {
    g.Name = ...;
    return g;
    });

  • @HemmingEducation
    @HemmingEducation Год назад

    Awesome!

  • @henrik3098
    @henrik3098 Год назад

    very good thank you my friend

  • @Thiago1337
    @Thiago1337 11 месяцев назад +1

    bro is teaching and doing asmr at the same time

    • @Tarodev
      @Tarodev  11 месяцев назад +1

      😉

  • @chadbaldwin652
    @chadbaldwin652 2 года назад +1

    OMG I FINALLY GET IT. THANK YOU. lol

  • @kopilkaiser8991
    @kopilkaiser8991 Год назад

    I just feel calm looking at these tutorials and even on the way I'm getting smarter and developing my code knowledge

  • @thatdotadev
    @thatdotadev 2 года назад

    If only this video would last for an hour showing examples. Amazing stuff

  • @kingreinhold9905
    @kingreinhold9905 2 года назад +3

    Dude you really have a special gift in teaching complicated topics... There's really no better way of breaking down this topic... Thanks for your good work!

  • @fulongfromthegrave
    @fulongfromthegrave 2 года назад +1

    underrated!

  • @ceroenblanco
    @ceroenblanco Год назад

    Thing I didn't know I needed to know

  • @CoffeeKavat
    @CoffeeKavat 4 месяца назад

    best unity tutorial!

  • @josbexerra8115
    @josbexerra8115 2 года назад +1

    Gracias Mister Tarodev que poder de las expresiones Lambda.....saludos de los andes peruanos

  • @kexell
    @kexell 2 года назад +1

    Good video

  • @pinguinpinguin-zv3fh
    @pinguinpinguin-zv3fh 7 месяцев назад

    make more of these you're an exam saviour....

  • @neilgargan
    @neilgargan Год назад +1

    "Cyberpunk destroyed our condition, just like it destroyed our dreams" - Tarodev

  • @betterlifeexe4378
    @betterlifeexe4378 2 года назад

    Been using linq for a while now. Love the lazy processing and REAL composition, not just employing a tool for composition, which is what the ':' really is for c#. there are more rules you have to follow for real composition, but it gives you so much. Which is one of the fundamental reasons why linq is AMAZEBALLZ.
    I would not be surprised in the least if the first intelligent aliens we meet have something startlingly like linq on the IL level. It is kind of close to a pure logical expression of the act of parsing related data. Maybe we should be pumping low level linq code into space, prove that there's at least some intelligent life stuck to this rock.

  • @castlecodersltd
    @castlecodersltd Год назад

    Great ☺

  • @breakchiller
    @breakchiller 2 года назад

    Damn good bro

  • @sipepguru
    @sipepguru 3 месяца назад

    Subbed.. lovely

  • @patrickp4175
    @patrickp4175 2 года назад

    damn, this is called lamda? so I did it on accident every time. Learned this on tutorials and didn't knew the other way thx for this :D

  • @kawaiianthony8090
    @kawaiianthony8090 2 года назад

    compact tutorial!

  • @taylor527
    @taylor527 5 месяцев назад

    I feel for you bro. I know that mood.

  • @ewwitsantonio
    @ewwitsantonio 2 года назад +4

    Nice video! Can you share your thoughts on using LINQ in Unity? Anything we should keep in mind?

    • @Tarodev
      @Tarodev  2 года назад +4

      Linq makes code clear and concise, but can sometimes be less performant than a standard for loop. But understand this can be the difference between it running 100,000 times a second instead of 105,000 times... so don't worry about performance until you have to because 99% of the time it will be fine.

    • @ewwitsantonio
      @ewwitsantonio 2 года назад +1

      @@Tarodev Thanks for the thoughts! Appreciate it

    • @NadjibBait
      @NadjibBait 2 года назад +1

      @@ewwitsantonio As a general rule, don't run LINQ in the game loop (Update method) for big collections/complex queries. But for initialization code (Start, Awake...) or code that does not run each frame, it's totally fine.

  • @markroworth5700
    @markroworth5700 2 года назад

    "just like it destroyed our hopes and dreams..." - genius.

  • @anshumanyadav24816
    @anshumanyadav24816 Год назад

    Big Like ( within start of a min ) watching this video

  • @Nature_Listener
    @Nature_Listener 2 года назад

    Hi could you explain unity physics with examples ? Thanks great content btw

  • @Lonchanick
    @Lonchanick Год назад

    belleza!

  • @GonziHere
    @GonziHere 2 года назад +1

    It's all fine and dandy, but hard to debug, which is why we don't use these as often. But maybe you have some debug tips?

  • @tonytran07
    @tonytran07 2 года назад

    Question: If there is a list of items separated by two categories (owned and not owned by the player), should I use forloop or lambda?
    My thought is, if I use lambda, I'll have to do it t twice, thus I presume it loops through the collection twice, whereas running the loop just goes through once to separate the list.
    Your thoughts?

  • @Jacob___THE_Jacob
    @Jacob___THE_Jacob 2 года назад

    cyberpunk burn lol, hilarious hahaha :)

  • @DerTimmey
    @DerTimmey 2 года назад +2

    oh boy 2:40 hit way to hard. great vid

  • @TroL0iO1er
    @TroL0iO1er 2 года назад +28

    This is more like a System.Linq tutorial than general lambda expressions. But anyways this is still good content.

  • @j0gi
    @j0gi 2 года назад

    2:40 yup, that's a like and sub right there

  • @TrailersYT
    @TrailersYT 2 года назад

    Hey, what if I wanted it to be based on luckPercentage? I have a dictionary of items, each item has a float luckPercentage
    Item 1 = 10.0
    Item 2 = 40.0
    Item 3 = 50.0
    So if I would want to take 1 item, item 2 and 3 would be the most often picked, and item 1 would be very rare. How can I achieve something like this?

  • @Lonchanick
    @Lonchanick Год назад +1

    More examples, nothing else!

  • @daswesen123
    @daswesen123 2 года назад +2

    Really nice tutorial. The only thing I disliked is that you used var so often. To understand the connections a little better the specific datatypes would have been better for me.

  • @dudds6699
    @dudds6699 Год назад

    I not only use lambda's I use them all of the time with Joins and GroupJoins good times

    • @dudds6699
      @dudds6699 Год назад

      Should have included a inner join and outer join IMO but venn diagrams in code might break your audience.

  • @jean-michel.houbre
    @jean-michel.houbre 2 года назад

    Hmm .. It's more of a tutorial on Linq, isn't it? But clear and useful!

  • @NewLondonMarshall
    @NewLondonMarshall 3 месяца назад

    Always give variables descriptive names because it's not just going to be you reading it. Other than that great video thank you!

  • @Fajah69
    @Fajah69 Год назад

    It still would want to know how to do it in a foreach loop.

  • @jkwong1978
    @jkwong1978 2 месяца назад

    can i change the value of the list using lambda ? like find the game named factorio, set its steam score to 9, using lambda, without creating a new list.

  • @ThunderaRafa433
    @ThunderaRafa433 12 дней назад

    you can use predicates lamda? right.

  • @drominito9354
    @drominito9354 Год назад

    You make it a simpler syntax that goes a bit with the Python direction

  • @user-ch7yu6ig5o
    @user-ch7yu6ig5o 2 года назад +1

    It was very hard for me, I don't understand this. But I guess it's cool.

  • @watercat1248
    @watercat1248 Год назад

    I'm curious what is the lambda I know it's I Greek letter λ but what is the lambda you talking on the video ?
    So basically lambda is the (>=) faction?
    If that the lambda faction it's something I use all the time with out even knowing the name of it