如何检查条件语句中的字符串值列表

本文关键字:字符串 列表 语句 条件 何检查 检查 | 更新日期: 2023-09-27 18:34:19

我正在尝试检查条件中字符串列表的值,而不是为每个或计数器循环创建一个。

例如

string extention = Path.GetExtension(attachment.Name).ToLower();
List<string> validExtentions = new List<string>() { ".tif", ".tiff", ".gif", ".jpeg", ".jif", ".png", ".pdf", ".txt", ".jpg" };
if(extention.Contains(validExtentions))
{
}

我想我可以使用一个.contains函数,它期待一个字符串而不是字符串列表,所以它不起作用。

如何检查条件语句中的字符串值列表

你只需要翻转你的变量。您检查您的extension是否包含在validExtensions列表中:

if(validExtensions.Contains(extension))
{
}

这个怎么样....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace EasyE
{
class Program
{
    static void Main(string[] args)
    {
        // Test strings
        List<extention> extentions = new List<extention>() { 
            new extention { FileName = "File1.jif" }, 
            new extention() { FileName = "File2.TIFF" },
            new extention() { FileName = "File3.txt" } };
        ///////////////
        Regex regex = new Regex(@"^.*'.(tif|tiff|gif|jpeg|jif)$",RegexOptions.IgnoreCase);
        if ((from ext in extentions where (ext.FileName.ToString() == regex.Match(ext.FileName.ToString()).Value) select ext).Count() > 0)
        {
        }
    }
}
class extention
{
    public string FileName { get; set; }
}
}