2013-03-21 36 views
0

我需要先取號從字符串,例如如何採取先數量從LINQ C#中的字符串

"12345 this is a number " => "12345" 
"123 <br /> this is also numb 2" => "123" 

爲我用C#代碼:

string number = ""; 
    foreach(char c in ebayOrderId) 
    { 
     if (char.IsDigit(c)) 
     { 
      number += c; 
     } 
     else 
     { 
      break; 
     } 
    } 
    return number; 

如何通過LINQ做同樣的事情?

謝謝!

+2

http://stackoverflow.com/a/15550651/1283124但使用'取(1)' – 2013-03-21 15:21:08

+0

對不起,但我需要別的東西 – ihorko 2013-03-21 15:23:04

+1

' 「有些值123
這也是麻木2」'應該產生'123'還是錯誤? – 2013-03-21 15:23:41

回答

8

你可以嘗試Enumerable.TakeWhile

ebayOrderId.TakeWhile(c => char.IsDigit(c)); 
+1

+1,優於正則表達式 – 2013-03-21 15:22:43

+0

是的,這正是我所需要的。謝謝! – ihorko 2013-03-21 15:24:21

+3

請注意,您可以將此縮短爲'ebayOrderId.TakeWhile(char.IsDigit)'。 – Lee 2013-03-21 15:35:10

2

您可以使用LINQ TakeWhile得到數字的列表,然後new string得到弦編號

var number = new string(ebayOrderId.TakeWhile(char.IsDigit).ToArray()); 
0

我會提高@大衛的回答。 (\d+)[^\d]*:一個數字後跟任何不是數字的數字。

您的號碼將是第一組:

static void Main(string[] args) 
{ 
    Regex re = new Regex(@"(\d+)[^\d]*", RegexOptions.Compiled); 
    Match m = re.Match("123 <br /> this is also numb 2"); 

    if (m.Success) 
    { 
     Debug.WriteLine(m.Groups[1]); 
    } 
} 
相關問題