Thursday, 15 March 2012

Linq to parse integers out of a string

Let me brief about collecting all the integer values from a string.
All these days, until now, I have been using the primitive 'for-loops' to traverse each and every character and then identify whether it is numeric or not, collect them in to array of characters/int.. and so on.


The linq is so powerful and easy to use. But take a look at the number of lines of code that have shorten down to, by using Linq.


string myString = "There is number 12 in me";
var myNmbr = myString.Where(c => char.IsNumeric(c));


NOTE:
The myNmbr will have 12 in the following manner
myNmbr[0] = 1
myNmbr[1] = 2
So use for each to merge it to a single string, or use .ToArray().ToString() at the end to give the same.
Output will be 12.


But what if you want only the first certain digits contained in a string??



string myString = "There is number 12 in me.But I also have 23";
var myNmbr = myString.Where(c => char.IsNumeric(c)).Take(3);



Output will be 122. 
The above will discard all numerics after the third number.