Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string of ints to list of ints with a TryParse

Tags:

c#

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.

like image 333
frenchie Avatar asked Apr 21 '12 12:04

frenchie


People also ask

Can you TryParse a string?

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.

What does int TryParse return?

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.

How do you use the TryParse method?

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.

What is difference between Parse and TryParse?

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 .


1 Answers

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.

like image 178
Andrew Cooper Avatar answered Sep 25 '22 20:09

Andrew Cooper