Mar 17, 2011

Refactor routine to use LINQ

Here is a function that does a bitwise XOR on a string

public string doIt(string input)
{
     var aChars = input.ToCharArray();
     var aCharsRes = new char[aChars.Length];

     for (int i = 0; i < aChars.Length; i++)
     {
          aCharsRes[i] = (char)(aChars[i] ^ 1);
     }
     return new string(aCharsRes);
}

Here is the re-factored one liner:

public string doItOneLiner(string input)
{
    return new string(input.ToCharArray().Select(s => (char)(s ^ 1)).ToArray());
}

Is it more readable? After getting used to LINQ, I guess.

No comments:

Post a Comment