I have this piece of code:
TheString = "443,432,546,4547,4445,2,132"; //actually, about 1000 entries
List<int> TheListOfIDs = new List<int>();
TheListOfLeadIDs = from string s in TheString.Split(',')
select Convert.ToInt32(s)).ToList<int>();
I know I can use a try catch to make sure the conversion doesn't throw an error but I was wondering how I could make this work with a TryParse in the linq statement.
Thanks.
TryParse(String, NumberStyles, IFormatProvider, Single) Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
To parse a string to DateTime in C#, you use the TryParse method and pass the string to be parsed and the type of DateTime you want it converted to. If the conversion is successful, then a DateTime object will be assigned to the out parameter. string input = "1/1/2022"; DateTime.
The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn't in a valid format, Parse throws an exception, but TryParse returns false .
TheListOfIDs = TheString.Split(',')
.Select(s =>
{
int i;
return Int32.TryParse(s, out i) ? i : -1;
}).ToList();
This will return a -1
for any failed conversion.
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