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.

Sunday, 1 January 2012

How to restrict a class from being instantiated?

How can you prevent a class from being instatiated, means, how to stop other classes/callers creating a new instace of an existing class?

There are two methods which are straight away
1) Declaring a class static, there by making all the members and properties static
2) Use a private constructor.

[OUT OF SYLLABUS]
The 2nd point is also used to follow Singleton Pattern (more on the pattern), but this is not to prevent creating any instances but to restrict only one instance of that class is created.