Checking for special characters using LINQ

wussy

Why on earth am I posting this?  For the simple reason of hoping if I take the time to put it down on "paper" that I will never have a need to use such a thing again.  Call it superstition.

Here is some specific background of why this came about.  A scenario came up where I was migrating some test data from one platform to another.  Some of the source data was encrypted (even in test system) and for my destination system I didn’t care about that data anyway.  If I came across any of that encrypted information and would just put blanks in the destination.  So in short if a string has special characters, nuke the data and write an empty string.

For what ever reason I wasn’t in a Regex mood and looked at LINQ for a solution.  Plus it is migration code so who really cares how optimal it is.

The first two lines of this extension method are something I read about and thought, "neat and when would I ever use it".  Basically Enumerable.Range will give you a range of of numbers with a starting number and a count.

IEnumerable lowRange = Enumerable.Range(0, 32);

The next albeit messy part takes the input string and converts it to a character array then takes each character and converts it to is ascii code representation.

IEnumerable enumerable = value.ToCharArray().Select(x => Convert.ToInt32(((int)x).ToString()));

The last bit was even more obscure than the range bit. Enumerable.Intersect "Produces the set intersection of two sequences."  If you have two lists, {1,2,3} and {3,4,5} the resultant list will be 3 with a .Count() of 1.

This was may more of a post than I hoped but hopefully someone will find it useful and I’ll will never have to think about it again!

File under:
blog comments powered by Disqus