Given this list of string values:
"12345"
, "6789a"
, "9876"
, "23467b"
How do we use a Linq statement in C# to select only the integers? In other words, we only want to return 12345
and 9876
.
You can filter your entries based on the return value of the Int32.TryParse
method:
int temp;
list.Where(x => int.TryParse(x, out temp));
Filter the list down to only those strings all characters of which are digits:
var filtered = list.Where(s => s.All(char.IsDigit));
An alternative is to use int.TryParse
as the filtering function, which has a number of subtle differences in behavior (the rules for what a valid integer is allow more than just digits, see the documentation).
If you want the results typed as integers, follow this up with .Select(int.Parse)
.
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