您当前的位置: 首页 >  c#

衣舞晨风

暂无认证

  • 0浏览

    0关注

    1156博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C# 使用LINQ、泛型、Index函数优化switch(或者多条if)语句

衣舞晨风 发布时间:2014-03-07 10:08:22 ,浏览量:0

背景:         判断某个变量是不是".txt.doc.xls.ppt.pdf"中的某一种格式,如果是则执行相应的操作。

方法一:使用泛型

readonly IList fNames = new List() {
             ".doc",
             ".txt",
             ".xls",
             ".ppt",
             ".pdf"
        };
private void Test(string fName)
{ 
    if(fNames.Contains(fName))
	{
        MessageBox.Show(fName);
    }
}
方法二:使用LINQ

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

如果是&&就用All

知识拓展:

LINQ 查询语法

Lambda表达式表达式树

LINQ查询的简单用法举例

方法三:使用Index函数

private void Test(string fName)
{
    string str = ".txt.doc.xls.ppt.pdf";
    if (str.IndexOf(fName) >= 0)
    {
        MessageBox.Show(fName);
    }
}
C# IndexOf 用法

关注
打赏
1647422595
查看更多评论
立即登录/注册

微信扫码登录

0.0790s