2016-11-16 96 views
6

如何從一個數組中刪除任何刪除字符串的字符串和只有整數,而不是C#從數組

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

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

回答

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

我對這個知之甚少,所以在效率方面比正則表達式更好呢? – Sean83

+0

謝謝,工作正常,SO系統設計爲等待5分鐘以接受您的答案。 – stom

+0

@ Sean83在這種情況下,它應該比RegEx更快 – fubo

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" 
+0

我只需要一個數組中的整數,這個答案可能會在將來幫助某人。謝謝。 – stom

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

爲什麼是動態類型?你對答案的回答有哪些好處? – Bidou

+0

動態使用值數據類型不乾淨,但在這種情況下,如果我們使用字符串數組,則結果將是相同的 – AmanMiddha

+0

如果不需要,請勿使用「動態」。在這種情況下,你必須使用'string'(即使它正在動態...) – Bidou