3

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?

beachnugga
  • 35
  • 3

3 Answers3

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();

Reference

Community
  • 1
  • 1
Nikhil K S
  • 806
  • 1
  • 13
  • 27
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