Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

By-pass else block of int.TryParse in Lambda Syntax

Suppose I have a string array and it may contain some data which can be parsed into an integer.

string[] strnums = { "2", "3", "hello", "5", "6", "8" };

I am trying to convert this string array into an integer array using LINQ Select method, something like this:-

int[] numbers = strnums.Select(x =>
                {
                    int temp = 0;
                    return int.TryParse(x, out temp) ? temp : 0;
                }).ToArray();

Output: 2,3,0,5,6,8 //Don't want 0 here

Here, in the else block of int.TryParse I had to give a default value (0), but I don't need this, that's why I titled my question as "By-Pass" the else part.

I have then used this query, and this is working fine, means it is not inserting unnecessary zero if string is not parsed:-

int[] numbers1 = strnums.Select(x => 
                {
                    int temp = 0;
                    bool isParsed = int.TryParse(x, out temp);
                    return new { temp, isParsed };
                })
                .Where(x => x.isParsed)
                .Select(x => x.temp)
                .ToArray();

But, this seems to be a lot of code, just for the sake of not considering the default value, I am projecting, filtering and again projecting. Is this the right approach?

like image 279
Rahul Singh Avatar asked Apr 23 '26 18:04

Rahul Singh


1 Answers

Why not implement in good old fashion - at least its easily understandable

        var nums = new List<int>();
        var numStrings = new List<string>{ "1", "2", "hello" };
        numStrings.ForEach(numString =>
        {
            int temp;
            if (int.TryParse(numString, out temp))
                nums.Add(temp);
        });

You can save some tiger balm!!!

like image 108
user635388 Avatar answered Apr 26 '26 07:04

user635388



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!