Home > Back-end >  Convert Method to LINQ lambda expression
Convert Method to LINQ lambda expression

Time:09-05

I have a validation function that receives two strings and makes a count compare, if the strings are the same size then it checks if the visible characters in the first string are the same as the second string.

private bool ValidateEncryptedText(string encrypted, string plain)
{
    if (plain.Count() != encrypted.Count())
        return false;
    else
    {
        for (int index = 0; index < plain.Count(); index  )
        {
            if (plain[index] != '*' && plain[index] != encrypted[index])
                return false;
        }
        return true;
    }
}

CodePudding user response:

Using string.Length instead of Count(), and using Zip to compare pairs, projecting to value tuples to avoid creating a lot of objects:

private bool ValidateEncryptedText(string encrypted, string plain) =>
    plain.Length == encrypted.Length &&
    plain.Zip(encrypted, (p, e) => ((p, e)))
         .All(pair => pair.p == '*' || pair.p == pair.e);

Note that by using All instead of counting the failures, we can return as soon as we find a difference. (It also makes the intention clearer, in my view.)

I would note that the variable names are perhaps misleading here - it would be really odd for plaintext and encrypted text to be the same.

CodePudding user response:

The new syntax will be

private bool ValidateEncryptedText(string encrypted, string plain) => plain.Count() != encrypted.Count() ? false : !(plain.Where((c, index) => c != '*' && c != encrypted[index]).Count() > 0);
  • Related