Am using the following code to split a string into a List<int>, however occasionally the string includes non integer values, which are handled differently.
An example string might be like: 1,2,3,4,x
code looks like:
List<int> arrCMs = new List<int>(strMyList.Split(',').Select(x => int.Parse(x)));
The problem is as soon as it hits the 'x' it throws an error because 'x' can't be parsed as an integer.
How can I make it ignore non integer values? I'm sure I should be able to do something with int.TryParse but can't quite figure it out.
Thanks
List<int> arrCMs = strMyList.Split(',')
.Select(possibleIntegerAsString => {
int parsedInteger = 0;
bool isInteger = int.TryParse(possibleIntegerAsString , out parsedInteger);
return new {isInteger, parsedInteger};
})
.Where(tryParseResult => tryParseResult.isInteger)
.Select(tryParseResult => tryParseResult.parsedInteger)
.ToList();
The first Select
in the above example returns an anonymous type that describes the result of int.TryParse
- that is, whether it was a valid integer, and if so, what the value was.
The Where
clause filters out those that weren't valid.
The second Select
then retrieves the parsed values from the strings that were able to be parsed.
Short and sweet, using int.TryParse
:
List<int> nums = list
.Split(',')
.Select(i =>
{
int val;
return int.TryParse(i, out val) ? (int?)val : null;
})
.Where(i => i.HasValue)
.Cast<int>()
.ToList()
Working Example: http://dotnetfiddle.net/4wyoAM
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