Reputation: 13739
I'd rather not throw an exception if the user enters one or more invalid doubles in a textbox. This is kind of what I'd like to do but it is wrong of course.
double myDouble[];
double.TryParse(textBox1.Text.Split(' '), out myDouble);
Upvotes: 2
Views: 5039
Reputation: 58615
How about this (almost) one liner?
double dbl;
IEnumerable<double> doubles =
textBox1.Text.Split(' ')
.Select(str => Double.TryParse(str, out dbl) ? dbl : 0.0);
Gotta love one liners :)
Upvotes: 1
Reputation: 6524
If you just want the first value, you can do this, too.
double myDouble[];
double.TryParse(textBox1.Text.Split(' ')[0], out myDouble);
Upvotes: 1
Reputation: 1898
how about...
var myDoubleList = new List<double>();
foreach(var doubleString in textBox1.Text.Split(' '))
{
double myDouble;
if (double.TryParse(doubleString, out myDouble))
myDoubleList.Add(myDouble);
}
Upvotes: 4
Reputation: 164331
Split first, then parse each value. Perhaps like this:
string numbers = "10 20 30 40 50";
int x = 0;
var values = from str in numbers.Split(' ')
where int.TryParse(str, out x)
select x;
Upvotes: 2
Reputation: 160952
TryParse()
is only trying to parse a single double value - you cannot use it with arrays. You could try and see if any number is invalid:
double myDouble;
bool parseFailed = textBox1.Text.Split(' ')
.Any( s => !double.TryParse(s, out myDouble));
Upvotes: 6