Using LINQ to parse the numbers from a string

iLemming picture iLemming · Aug 13, 2010 · Viewed 11.7k times · Source

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 6 7 23 1"

Result must be "67231"

And even slight harder: Can we get only first three numbers?

Answer

Carlos Muñoz picture Carlos Muñoz · Aug 13, 2010

This will give you your string

string result = new String("y0urstr1ngW1thNumb3rs".
    Where(x => Char.IsDigit(x)).ToArray());

And for the first 3 chars use .Take(3) before ToArray()