Tuesday, May 12, 2009

Weird things with LINQ - stripping unwanted unicodes.

So here was my problem, I needed to strip any unicode characters above 255.
At first I thought of using a regular expression to do a replace with but then the exclusion clause might be a bit long. Then I thought "can I do it with LINQ?".

Here is the result:

  private static string StripUniCode(string originalText)

        {

            var chars = originalText.ToCharArray();

            var result = from chr in chars

                        where chr <= 255

                        select chr;

            StringBuilder sb = new StringBuilder();

            sb.Append(result.ToArray<char>());

 

            return sb.ToString().Trim();

 

        }


Not brilliant but what the hell. You gotta love LINQ.
 

    

No comments: