Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into List<int> ignore none int values

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

like image 254
HuwD Avatar asked Apr 17 '14 15:04

HuwD


2 Answers

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.

like image 70
AlexC Avatar answered Oct 31 '22 14:10

AlexC


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

like image 41
Andrew Whitaker Avatar answered Oct 31 '22 13:10

Andrew Whitaker