When parsing a string to an int you want to use int.TryParse
to make sure it won't throw an exception. In linq you can do it this way:
var result = s.TheListOfStrings.Split(',')
.Select(i => (int.TryParse(i, out var value), value))
.Where(pair => pair.Item1) // remove items that failed to be parsed
.Select(pair => pair.value) // take the parsed value
.ToList();
This fixes the cases of the empty items from the split (you can still add the RemoveEmptyEntries
flag) and also, in case an item is not a valid integer it won't parse it.
Notice that the first ToList()
that you added is not needed.
As you are using a pre C# 7.0 version then you should:
int value;
var result = s.TheListOfStrings.Split(',')
.Select(i => new { Succeeded = int.TryParse(i, out value), Value = value })
.Where(pair => pair.Succeeded) // remove items that failed to be parsed
.Select(pair => pair.Value) // take the parsed value
.ToList();
Difference:
In your question you stated: The problem is that sometimes TheListOfStrings
is null and I think that's what triggers the error.
This will not be the cause for the error as if it was you would have received a NullReferenceException
.
To cope with that you can:
- Use the
?.
operator (and then the result might be null
instead of an empty collection.
Check if it is null
:
var result = s.TheListOfStrings == null ?
Enumerable.Empty<int> () :
/*The linq query above*/;