I got a textbox that should be filled with int of 4 number, something like this [0000, 4444, 5555, 6666]. I need to get where is the comma and then put the 4 numbers in a var. Can you help me?
Asked
Active
Viewed 451 times
3
-
Have you tried String.Split()? (http://msdn.microsoft.com/de-de/library/system.string.split%28v=vs.110%29.aspx) – DIF Apr 11 '14 at 08:12
-
I just discovered it :) thank you! – beachnugga Apr 11 '14 at 08:23
3 Answers
8
Have you tried String.Split
?
string[] allTokens = textBox1.Text.Split(new []{ ','}, StringSplitOptions.RemoveEmptyEntries);
int[] allInts = Array.ConvertAll<string, int>(allTokens, int.Parse);
If the format can be invalid you can use int.TryParse
:
int num = 0;
int[] allInts = allTokens
.Where(s => int.TryParse(s, out num))
.Select(s => num)
.ToArray();

Tim Schmelter
- 450,073
- 74
- 686
- 939
3
You will get int list
var numbers = TextBox1.Text.Split(',').Select(str => {
int value;
bool success = int.TryParse(str, out value);
return new { value, success };
})
.Where(pair => pair.success)
.Select(pair => pair.value).ToList();

Community
- 1
- 1

Nikhil K S
- 806
- 1
- 13
- 27
-
2nice, I like the lambda, but what happens when there is not an int? – Christian Sauer Apr 11 '14 at 08:13
2
You could try
var resultArr = tb.split(",");
foreach (elem in resultArr)
{
int i;
if (int.tryparse(elem, out i))
// do something with i
else
// that was not an int
}

Mo Patel
- 2,321
- 4
- 22
- 37

Christian Sauer
- 10,351
- 10
- 53
- 85