c#从数组中删除字符串

时间:2016-11-16 09:31:57

标签: c# arrays string

如何从数组中删除任何字符串,而只使用整数

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

我有

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

我想要

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

我试过

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

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

但是在第一个元素之前有一个逗号,有没有更好的方法来删除字符串?

3 个答案:

答案 0 :(得分:10)

这将选择所有可以解析为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();

答案 1 :(得分:0)

同样支持double我会这样做:

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

然后

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

答案 2 :(得分:0)

试试这个

  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!
                    }
                }