Can TryParse be used in a Lambda in a LINQ method?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    Can TryParse be used in a Lambda in a LINQ method?

    <edited by mod>

    Having this expression...

    Code:
    int[] n = (from ch in "48727" select int.Parse(ch.ToString())).ToArray();
    I'm slowly learning this crazy Linq thing... maybe. Actually, this leads me to a question... is there a way to use a lambda here to run it through a TryParse? I might be a little confused on how lamdas work, but I was thinking something like...

    Code:
    int [] n = (from ch in "48727" select (ch => int r; if (int.TryParse(ch.ToString(), out i) return i;)).ToArray();
    ... or something to that effect. That code doesn't compile, so am I way out to lunch or is there a way to do it?

    *Edit: Haha, curtis read my mind... kinda. How would you use it with TryParse?
    Last edited by Curtis Rutland; Nov 3 '10, 03:43 PM. Reason: Edited to make into a question.
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    Yes, there is. You'd use a multi-line lambda:

    Code:
    int[] nums = "123b5".Select(x =>
    {
        int r;
        if (int.TryParse(x.ToString(), out r))
            return r;
        else
            return -1;
    }).ToArray();
    Note I just formatted it that way for readability, you could have it all on one line if you like.

    With those lambdas, you enclose them in { } brackets. But there's no explicit return then; you have to manually return a value.

    Also, in this case, you need a "default" value, since you have to return something, even when it doesn't parse.

    Comment

    • Christian Binder
      Recognized Expert New Member
      • Jan 2008
      • 218

      #3
      Gary's question led me to try something crazy, which was working quite good:

      Code:
      int dummy = 0;
      int[] nums = "123".Where(c => int.TryParse(c.ToString(), out dummy)).Select(x => dummy).ToArray();
      But that's just for fun and only works because of dereferred execution; the following won't work.
      Code:
      int[] nums = "123".Where(c => int.TryParse(c.ToString(), out dummy)).ToArray().Select(x => dummy).ToArray();
      That's because the ToArray in the middle executes for all three chars in "123" and dummy gets the last value (3).

      So never use this ;-)

      Comment

      • GaryTexmo
        Recognized Expert Top Contributor
        • Jul 2009
        • 1501

        #4
        Thanks guys. It seems I was on the right track, I was just missing the curly braces (and the now obvious default return). With that parameter, what type is x, or is it just that var type? Is it allowed to give it an explicit type or is the convention to leave it as var, then just try to cast it inside your lambda?

        Also, Linq is confusing...

        Comment

        • Christian Binder
          Recognized Expert New Member
          • Jan 2008
          • 218

          #5
          It's (the result) implicitely typed to char.
          That's because string implements IEnumerable<cha r>.
          (There's no "var-type", var is just an identifier but it has a strong type like int, char!)

          You can implicitely type it
          Code:
          int[] nums = "123b5".Select<char, int>((char x) =>
          {
            int r;
            if (int.TryParse(x.ToString(), out r))
              return r;
            else
              return -1;
          }).ToArray();

          Comment

          • GaryTexmo
            Recognized Expert Top Contributor
            • Jul 2009
            • 1501

            #6
            Ahhhhh, it's becoming someone slightly less murky ;)

            I'll be honest, I'm not sure how I like this Linq thing, but it's good to try to know and understand regardless of my feelings on the matter. Thanks guys!

            Comment

            • Curtis Rutland
              Recognized Expert Specialist
              • Apr 2008
              • 3264

              #7
              I, for one, love it. It's totally changed the way I program.

              As for Lambdas, they're basically shortcuts for delegates.

              These two lines are basically identical:

              Code:
              var nums = "12345".Select(x => int.Parse(x.ToString())).ToArray();
              int[] nums2 = "12345".Select(delegate(char x) { return int.Parse(x.ToString()); }).ToArray();
              Lambdas just have lots of implicit typing and shortcut syntax.

              Lambda parameters are implicitly typed based on the signature of the expected delegate. Also, if they are a single line (not enclosed in brackets) and the method is not of type void, the result of the single statement is returned by default.

              It's just shortcut syntax.

              If you don't like the free format language of LINQ, I'd say start using the Extension methods, like I usually do. I only use the free format syntax for the things that are more easily expressed with it, like complicated groupings.

              Also, strings aren't the best example to use it on, because they're confusing. Strings are treated as IEnumerable<cha r>, so just pretend that where you see a string, it's actually a char array.

              Comment

              • GaryTexmo
                Recognized Expert Top Contributor
                • Jul 2009
                • 1501

                #8
                Yea, as I use it, it makes more and more sense, bit by bit :D

                I think I mentioned it a while back but yea... the shortcut is nice, I just fear that it adds a layer of confusion. An experienced .NET programmer can read and understand the non-Linq version quite easily, but they may not understand the Linq version. I'd imagine that someone who hadn't had much Linq experience trying to debug a Linq heavy program could get bogged down? Just an extra layer.

                But for those who do understand it, saving yourself a lot of otherwise repetitive code could be quite helpful! It's quite nice that we've got you folks who do understand it here to help us :D I know I'll likely have more questions for you on Linq in the future, lol.

                Comment

                • Curtis Rutland
                  Recognized Expert Specialist
                  • Apr 2008
                  • 3264

                  #9
                  An experienced .NET programmer can read and understand the non-Linq version quite easily, but they may not understand the Linq version. I'd imagine that someone who hadn't had much Linq experience trying to debug a Linq heavy program could get bogged down? Just an extra layer.
                  You could say the same thing about Generics though. An experienced .NET Framework 1.1 developer would understand how to do things without generics, and would be bogged down debugging one with them.

                  But it's not just an "extra layer", it's a core feature of the language now. To the people that want to stay in the past (not you, Gary, I know that), I say fine, but don't complain that the rest of us progress.

                  Basically, what I'm saying is that if it adds confusion for you, learn what it's doing so you're not confused, don't just shut the door on something so useful and productive.

                  That's actually the thing I love about C#. The developers are willing to push the language, to evolve it, to grow it in new directions. To the anti-change people, Java is wonderful. It moves at a glacial pace, while C# 4.0 barely resembles C# 1.0.

                  Comment

                  • GaryTexmo
                    Recognized Expert Top Contributor
                    • Jul 2009
                    • 1501

                    #10
                    If by generics, you mean the whole T thing, I believe that's an ANSI C concept, templates? Just did a quick google... http://www.codersource.net/c/c-tutor...templates.aspx Same idea. But yes, I see your point, though I feel like Linq is this point on steroids :D

                    Also, you do have to admit that the only reason it's a "core" feature is because Microsoft called it so. It seems more like a layering of functionality as, with what you guys have shown me of extensions, it just wraps up code and throws it on a type. The lambda thing is just a short-hand, inline version of a method?

                    That said, I suppose the same could be said for everything, and I'm so done writing in assembly :P

                    Anyway, I'm not saying it's dumb, it just seems like another programming language within the programming language. You can't say you know C# .NET anymore because you may not know Linq. Does that make sense?

                    It is cool though, if confusing to people who haven't seen it before. Tough to keep up sometimes ;)

                    Aaaaanyway, no I don't mean

                    Comment

                    • Curtis Rutland
                      Recognized Expert Specialist
                      • Apr 2008
                      • 3264

                      #11
                      Also, you do have to admit that the only reason it's a "core" feature is because Microsoft called it so.
                      Yes, but who better to say what is a feature than the people creating the language? I guess I don't understand this. They're the ones that make everything else a feature too.

                      You could call LINQ a metalanguage, and you wouldn't be wrong. But just remember, it's both the present and the future for .NET. It's the direction they're going, so best get on the train now while you have options rather than be left at the platform wondering where everyone else went.

                      You can't say you know C# .NET anymore because you may not know Linq. Does that make sense?
                      I'd agree, but at the same time, that's true for any new feature. I guess it could have been said (since 2.0) that you didn't know C# if you didn't know delegates. That's very true, because delegates are a core concept that are widespread across the entire language, but most people didn't need them except for events.

                      LINQ brought them out into everyone's face (although it also provided a shortcut for using them). That's why it feels so confusing to some people, and so natural to others. The core of what LINQ is was already there in .NET 2.0. That core just wasn't as visible to everyone as it is now.

                      Comment

                      • GaryTexmo
                        Recognized Expert Top Contributor
                        • Jul 2009
                        • 1501

                        #12
                        Bah, looks like my last post got cut off for some reason. Oh well, I don't remember what I wrote after that anyway :D

                        I guess what I'm getting at with the core feature is that there's a difference between Linq, which appears to be an alternate way of doing something, and things like what's in System.IO, which are (for the most part) the only way to do things.

                        Anyway, it's been an interesting discussion. I still have reservations but that doesn't mean it's not worth learning ;)

                        Comment

                        Working...