-2

I have a string list array that contains strings. Either the values will be a name or number. For example the contents could be:

stringList[0]="Mary"
stringList[1]="John"
stringList[2]="4564321"
stringList[3]="Steven"

I want to append the contents of the list to a string which I have done through a simple loop but if a number is encountered I want that number to be popped out and handled in a different method and then have the original loop continue looking for strings and appending. Essentially I want to append the non numbers and take the numbers and do something else with them. What functions or tricks can I do so when it is going through the list it will be able to identify a string as a number?

Icebreaker
  • 277
  • 1
  • 6
  • 13
  • 2
    What have you tried so far? Seems like some basic research would set you on the right path. Where are you stuck? – mason Dec 02 '14 at 19:36
  • Can you provide a sample of the output you want? You might be able to use the `.Where()` Linq method to filter out the items based on your condition. – Mike Christensen Dec 02 '14 at 19:38
  • you could have solved this as well using the `char.IsNumberic` Function or `char.IsAlpha` function.. Google works wonders if it's used properly fyi.. please show more effort on your part opposed to getting in a state of panic and expecting others to provide you with a quick fix ..the best way to learn is by doing – MethodMan Dec 02 '14 at 19:57
  • `string tempStr = "Mary";` `bool _isNumeric = tempStr.ToCharArray().All(x => Char.IsDigit(x));` – MethodMan Dec 02 '14 at 19:59

2 Answers2

4

As long as the string is always a number (not numbers and letters mixed), you an use one of the various TryParse methods. I'll use int in my example, but you can use whichever fits your needs:

int value;

foreach(var s in stringList)
{
    if(int.TryParse(s, out value))
    {
        // s was a number, the parsed result is in value
    }
    else
    {
        // s was something else
    }
}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

You can use int.TryParse to determine if it's a number and get its value.

int intValue;
if (int.TryParse(str, out intValue))
    // handle as int
else
    // handle as string
Tim S.
  • 55,448
  • 7
  • 96
  • 122