EasyE
EasyE

Reputation: 580

How to check a list of string values in a condition statement

I am trying to check the value of a list of string in a condition, with out creating a for each or counter loop.

For Example

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

}

I thought I could use a .contains function which is expecting a string not a list of string so it will not work.

Upvotes: 0

Views: 857

Answers (2)

User9995555
User9995555

Reputation: 1556

How about this....

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

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245399

You just need to flip your variables. You checking if your extension is contained inside the list of validExtensions:

if(validExtensions.Contains(extension))
{

}

Upvotes: 3

Related Questions