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?
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!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With