stom stom - 22 days ago 11
C# Question

c# remove strings from an array

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 ?

Answer

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