So I have an IEnumerable<string>
which can contain values that can be parsed as int
, as well as values that cannot be.
As you know, Int32.Parse
throws an exception if a string cannot be changed to an int, while Int32.TryParse
can be used to check and see if the conversion was possible without dealing with the exception.
So I want to use a LINQ query to one-liner parse those strings which can be parsed as int, without throwing an exception along the way. I have a solution, but would like advice from the community about whether this is the best approach.
Here's what I have:
int asInt = 0; var ints = from str in strings where Int32.TryParse(str, out asInt) select Int32.Parse(str);
So as you can see, I'm using asInt
as a scratch space for the call to TryParse
, just to determine if TryParse
would succeed (return bool). Then, in the projection, I'm actually performing the parse. That feels ugly.
Is this the best way to filter the parseable values in one-line using LINQ?
In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.
Perhaps the easiest and the most reliable way to check whether a String is numeric or not is by parsing it using Java's built-in methods: Integer. parseInt(String) Float.
parseInt() The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Type casting lowers the range of possible values. Type casting changes the type of the value stored. Which is a valid way to parse a String as an int? A double with the value of 20.5 is cast to an int.
It's hard to do that in query syntax, but it's not too bad in lambda syntax:
var ints = strings.Select(str => { int value; bool success = int.TryParse(str, out value); return new { value, success }; }) .Where(pair => pair.success) .Select(pair => pair.value);
Alternatively, you may find it worth writing a method which returns an int?
:
public static int? NullableTryParseInt32(string text) { int value; return int.TryParse(text, out value) ? (int?) value : null; }
Then you can just use:
var ints = from str in strings let nullable = NullableTryParseInt32(str) where nullable != null select nullable.Value;
It's still two codelines, but you can shorten up your original a little:
int asInt = 0; var ints = from str in strings where Int32.TryParse(str, out asInt) select asInt;
Since the TryParse already runs at the time of the select, the asInt
variable is populated, so you can use that as your return value - you don't need to parse it again.
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