Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all integers in list of strings

Tags:

c#

int

parsing

linq

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.

like image 806
Alex Avatar asked Nov 28 '22 17:11

Alex


2 Answers

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));
like image 168
Douglas Avatar answered Dec 13 '22 18:12

Douglas


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).

like image 29
Jon Avatar answered Dec 13 '22 17:12

Jon