C# uses LINQ, generics, and Index functions to optimize switch (or multiple if) statements

黄舟
Release: 2017-02-21 10:55:29
Original
2282 people have browsed it

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);
    }
}
Copy after login

Method 2: Use LINQ

private void Test(string fName)
{
    if (new string[] { ".doc", ".txt", ".xls" }.Any(x => fName == x))
    {
        MessageBox.Show(fName);
    }
}
Copy after login

If it is &&, use All

knowledge Extension:

LINQ query syntax

Lambda expression expression tree

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);
    }
}
Copy after login

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)!




Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template