[英]Convert Method to LINQ lambda expression
我有一個驗證 function 接收兩個字符串並進行計數比較,如果字符串大小相同,則它檢查第一個字符串中的可見字符是否與第二個字符串相同。
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;
}
}
使用string.Length
代替Count()
,並使用Zip
比較對,投影到值元組以避免創建大量對象:
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);
請注意,通過使用All
而不是計算失敗次數,我們可以在發現差異后立即返回。 (在我看來,這也使意圖更加清晰。)
我會注意到變量名稱在這里可能會產生誤導——明文和加密文本相同會很奇怪。
新語法將是
private bool ValidateEncryptedText(string encrypted, string plain) => plain.Count() != encrypted.Count() ? false : !(plain.Where((c, index) => c != '*' && c != encrypted[index]).Count() > 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.