C # uses LINQ, Generics, and index functions to optimize switch (or multiple IF) statements

Source: Internet
Author: User
Background:
Determine if a variable is a format in ". Txt.doc.xls.ppt.pdf", and if so, perform the appropriate action.

Method One: 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 two: Use LINQ

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

If it's &&, use all

Knowledge Development:

LINQ query syntax

Lambda expression-expression tree

Examples of simple usages of LINQ queries

Method Three: Use the 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 the switch (or multiple if) statements, and more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.