简体   繁体   English

有没有办法检查字符串是否不等于多个不同的字符串?

[英]Is there a way to check if a string is not equal to multiple different strings?

I want to validate a file uploader, by file extension. 我想通过文件扩展名验证文件上传器。 If the file extension is not equal to .jpg, .jpeg, .gif, .png, .bmp then throw validation error. 如果文件扩展名不等于.jpg,.jpeg,.gif,.png,.bmp,则抛出验证错误。

Is there a way to do this without looping through each type? 有没有办法在不循环每种类型的情况下执行此操作?

Just build a collection - if it's small, just about any collection will do: 只需构建一个集合 - 如果它很小,几乎任何集合都可以:

// Build the collection once (you may want a static readonly variable, for
// example).
List<string> list = new List<string> { ".jpg", ".jpeg", ".gif", ".bmp", ... };

// Later
if (list.Contains(extension))
{
    ...
}

That does loop over all the values of course - but for small collections, that shouldn't be too expensive. 这确实会循环所有的值 - 但对于小型集合,这不应该太昂贵。 For a large collection of strings you'd want to use something like HashSet<string> instead, which would provide a more efficient lookup. 对于大量字符串,您需要使用类似HashSet<string>东西,这样可以提供更有效的查找。

You can use !Regex.IsMatch(extension, "^\\.(jpg|jpeg|gif|png|bmp)$") 你可以使用!Regex.IsMatch(extension, "^\\.(jpg|jpeg|gif|png|bmp)$")

but internally somehow it will still loop 但在内部某种程度上它仍将循环

将扩展名粘贴在集合中,然后检查文件的扩展名是否在该集合中。

It will require a loop, but you can do this with LINQ (hides the loop) 它需要一个循环,但你可以使用LINQ(隐藏循环)

ie: 即:

using System.Linq;

private readonly string[] _matches = new[] { ".jpg", ".bmp", ".png", ".gif", ".bmp" };    

// Assumes extension is in the format ".jpg", "bmp", so trim the
// whitespace from start and end
public bool IsMatch(string extension)
{
     return _matches.Contains(extension);
}

It could also be done with Regex but I'm no regex wizz so I'll leave that to another poster :) 它也可以用正则表达式完成,但我不是正则表达式wizz所以我会把它留给另一张海报:)

Use the following 2 extensions. 使用以下2个扩展名。 I wrote about them in an article on CodeProject. 我在CodeProject上写了一篇关于它们的文章。 Here you go: http://www.codeproject.com/KB/dotnet/MBGExtensionsLibrary.aspx 您可以访问: http//www.codeproject.com/KB/dotnet/MBGExtensionsLibrary.aspx

        public static bool In<T>(this T t, IEnumerable<T> enumerable)
        {
            foreach (T item in enumerable)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

        public static bool In<T>(this T t, params T[] items)
        {
            foreach (T item in items)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

Of course it still requires a loop, but the good thing is you don't have to do that work. 当然它仍然需要循环,但好的是你不必做那项工作。 It also means you don't have to write code like this: 这也意味着您不必编写如下代码:

if (myString == "val1" ||
   myString == "val2" ||
   myString == "val3" ||
   myString == "val4" ||
   myString == "val5")
   {
      //Do something
   }

There's an answer to that on StackOverflow already. 已经在StackOverflow上得到了答案。 HERE But I'd suggest you take the path of constructing a list of extensions and then checking agains each one of those. 这里但我建议你采取构建扩展列表的路径,然后再检查每一个扩展。 Regex would be more costly than that and would internally do roughly the same. 正则表达式会比这更昂贵,内部会大致相同。

You can use switch statement to validate file extension: 您可以使用switch语句验证文件扩展名:

protected bool IsValidExtension(string extension)
{
  switch (extension.ToLower())
  {
    case ".jpg":
    case ".jpeg":
    case ".gif":
    case ".png":
    case ".bmp":
      return true;

    default:
      return false;
  }
}

Regular Expression. 正则表达式。

    string fx = "jpg";
    if (!Regex.IsMatch(fx, "^\.?(jpg|jpeg|gif|png|bmp)$", RegexOptions.IgnoreCase))
    {

    }

also, to get the file extension, use 另外,要获取文件扩展名,请使用

string fn= file.FileName;
if (fn.Contains("\\")) 
    fn= fn.Substring(fn.LastIndexOf("\\") + 1);

string fx = fn.Substring(0, fn.LastIndexOf('.'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM