You can use int.TryParse
string[] values = { "1", "2", "3a","4" }; int i = int.MinValue; List<int> output = values.Where(s => int.TryParse(s, out i)) .Select(s => i) .ToList();
Demo
However, Eric Lippert will not be surprised . Therefore, if you do not want to (ab) use side effects, this will be the best approach:
Create an extension method, for example:
public static class NumericExtensions { public static int? TryGetInt(this string item) { int i; bool success = int.TryParse(item, out i); return success ? (int?)i : (int?)null; } }
Then you can write this:
List<int> output = values.Select(s => s.TryGetInt()) .Where(nullableInt => nullableInt.HasValue) .Select(nullableInt => nullableInt.Value) .ToList();
Tim schmelter
source share