Using LINQ to parse the numbers from a string

前端 未结 7 1482
忘掉有多难
忘掉有多难 2021-02-19 22:00

Is it possible to write a query where we get all those characters that could be parsed into int from any given string?

For example we have a string like: \"$%^DDFG

7条回答
  •  醉话见心
    2021-02-19 22:54

    The following should work.

    var myString = "$%^DDFG 6 7 23 1";
    
    //note that this is still an IEnumerable object and will need
    // conversion to int, or whatever type you want.
    var myNumber = myString.Where(a=>char.IsNumber(a)).Take(3);
    

    It's not clear if you want 23 to be considered a single number sequence, or 2 distinct numbers. My solution above assumes you want the final result to be 672

提交回复
热议问题