Rahul Singh

Rahul Singh

  • NA
  • 1.4k
  • 584.6k

In LINQ Lambda query how to skip else block of int.TryParse

Jan 6 2015 9:29 AM

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.

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?


Answers (2)