8

How can i remove any strings from an array and have only integers instead

string[] result = col["uncheckedFoods"].Split(',');

I have

[0] = on;      // remove this string
[1] = 22;
[2] = 23;
[3] = off;      // remove this string
[4] = 24;

I want

[0] = 22;
[1] = 23;
[2] = 24;

I tried

var commaSepratedID = string.Join(",", result);

var data = Regex.Replace(commaSepratedID, "[^,0-9]+", string.Empty);

But there is a comma before first element, is there any better way to remove strings ?

3 Answers 3

12

This selects all strings which can be parsed as int

string[] result = new string[5];
result[0] = "on";      // remove this string
result[1] = "22";
result[2] = "23";
result[3] = "off";      // remove this string
result[4] = "24";
int temp;
result = result.Where(x => int.TryParse(x, out temp)).ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know much about this so is this better than regex method in terms of efficiency?
Thank you, works fine , SO system is designed to wait 5 minutes to accept your answer.
@Sean83 in this case it should be faster compared to RegEx
0

To also support double I would do something like this:

public static bool IsNumeric(string input, NumberStyles numberStyle)
{
   double temp;
   return Double.TryParse(input, numberStyle, CultureInfo.CurrentCulture, out temp);
}

and then

string[] result = new string[] {"abc", "10", "4.1" };
var res = result.Where(b => IsNumeric(b, NumberStyles.Number));
// res contains "10" and "4.1"

1 Comment

I only need integers from an array, this answers might help someone in future. Thank you.
0

Try this

  dynamic[] result = { "23", "RT", "43", "67", "gf", "43" };

                for(int i=1;i<=result.Count();i++)
                {
                    var getvalue = result[i];
                    int num;
                    if (int.TryParse(getvalue, out num))
                    {
                        Console.Write(num);
                        Console.ReadLine();
                        // It's a number!
                    }
                }

5 Comments

why a dynamic type? what is the benefit of your answer over the accepted one?
dynamic use when values data type are not clean but in this case if we use String array then result will be same
Never use dynamic if not needed. In this case, you have to use string (even if it is working with dynamic...)
ok thanks, but when i have no idea which type of data will come dynamically in arrray then what should i do?
if you have any idea or example related to this , then it will be very helpful for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.