簡體   English   中英

c#從數組中刪除字符串

[英]c# remove strings from an array

我如何從數組中刪除任何字符串,而只有整數

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

但是在第一個元素之前有一個逗號,有沒有更好的方法來刪除字符串?

這將選擇所有可以解析為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();

為了支持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"

試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM