Background:
Determine whether a variable is in a certain format in ".txt.doc.xls.ppt.pdf", and if so, perform the corresponding operation.
Method 1: Use generics
readonly IList<String> fNames = new List<String>() { ".doc", ".txt", ".xls", ".ppt", ".pdf" }; private void Test(string fName) { if(fNames.Contains(fName)) { MessageBox.Show(fName); } }
Method 2: Use LINQ
private void Test(string fName) { if (new string[] { ".doc", ".txt", ".xls" }.Any(x => fName == x)) { MessageBox.Show(fName); } }
If it is &&, use All
knowledge Extension:
LINQ query syntax
Simple usage example of LINQ query
Method 3: Use Index function
private void Test(string fName) { string str = ".txt.doc.xls.ppt.pdf"; if (str.IndexOf(fName) >= 0) { MessageBox.Show(fName); } }
C# IndexOf Usage
The above is the content of C# using LINQ, generics, and Index functions to optimize switch (or multiple if) statements , for more related content, please pay attention to the PHP Chinese website (www.php.cn)!