frenchie
frenchie

Reputation: 51997

string of ints to list of ints with a TryParse

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.

Upvotes: 7

Views: 7179

Answers (4)

Arion
Arion

Reputation: 31249

You could do it like this:

string TheString = "443,432,546,4547,4445,2,132"; //actually, about 1000 entries
int temp=0;
var TheListOfIDs= TheString
                  .Split(',')
                  .Where (ts =>int.TryParse(ts,out temp))
                  .Select (ts =>temp )
                  .ToList();

Upvotes: 4

David Brabant
David Brabant

Reputation: 43539

Warning: not tried.

string[] myString = TheString.Split(',');

int leadId;
var theListOfLeadIds = (from myString in myString where int.TryParse(myString, out leadId) select int.Parse(myString)).ToList<int>();

Meaning that you will only get value successfully parsed ...

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32586

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.

Upvotes: 10

MarcinJuraszek
MarcinJuraszek

Reputation: 125640

TheListOfLeadIDs = (from string s in TheString.Split(',')
                    let value = 0
                    where int.TryParse(s, out value)
                    select value).ToList<int>();

Upvotes: 7

Related Questions