享受LINQ:判斷一組文字是否在字符串中同時出現的最簡單方法


需求是這樣的:不允許在一個字符串中同時出現"博", "客", "園", "團", "隊"這5個文字。

如果不用LINQ,代碼寫起來會很啰嗦:

var teststr = "博2客0園1團4隊.";
if (teststr.IndexOf("") >= 0 &&
    teststr.IndexOf("") >= 0 &&
    teststr.IndexOf("") >= 0 &&
    teststr.IndexOf("") >= 0 &&
    teststr.IndexOf("") >= 0)
{
    //...
}

而用LINQ,代碼立馬變得簡潔:

var teststr = "博2客0園1團4隊.";           
var cmt = new string[] { "", "", "", "", "" };
if (cmt.All(teststr.Contains))
{
    //...
}

LINQ讓寫代碼變得更享受,也更具表達力。

【參考】

Using C# to check if string contains a string in string array


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM