Home  >  Article  >  Backend Development  >  C# uses LINQ, generics, and Index functions to optimize switch (or multiple if) statements

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

黄舟
黄舟Original
2017-02-21 10:55:292283browse

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

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);
    }
}

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




Statement:
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