Reputation: 35861
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
.
Upvotes: 4
Views: 4511
Reputation: 460208
One way:
IEnumerable<int> ints = strings.Where(str => str.All(Char.IsDigit))
.Select(str => int.Parse(str));
This selects only strings where all chars are digits. Then it parses them to int
.
A better way is to use this extension:
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 use this query:
IEnumerable<int> ints = strings.Select(str => str.TryGetInt())
.Where(nullableInt => nullableInt.HasValue)
.Select(nullableInt => nullableInt.Value);
Upvotes: 6
Reputation: 33139
The TryParse
method of int
is the most reliable indicator that you have a proper number.
Use it like this:
int number = 0;
var selected = list.Where(x => int.TryParse(x, out number)).ToList();
Upvotes: 4
Reputation: 437504
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)
.
Upvotes: 7
Reputation: 54897
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));
Upvotes: 14