Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# remove strings from an array

Tags:

arrays

string

c#

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 ?

like image 720
Shaiju T Avatar asked Nov 16 '16 09:11

Shaiju T


1 Answers

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();
like image 53
fubo Avatar answered Oct 22 '22 05:10

fubo