I am querying results from the database. I have a column called Extension which can either be a gif, txt, docx etc. I am using Linq and Entity Framework Core. The extension is provided by a user or anyone searching and I understand I can just add multiple OR to my query but I have made a list of strings like below:
List<string> ImageFormats = new List<string>();
ImageFormats.Add("png");
ImageFormats.Add("jpg");
ImageFormats.Add("jpeg");
ImageFormats.Add("tiff");
ImageFormats.Add("gif");
Now I can add multiple OR statements to my query like below:
var results = _database.Documents
.Where(d => d.Extension == "png" || d.Extension == "png")
.ToList();
But I want a different approach where I can use my list of extensions above on the query like below:
var results = _database.Documents
.Where(d => d.Extension == ImageFormats)
.ToList();
Yes the code above cannot work. Is there a way something like this can be achieved?
CodePudding user response:
It really looks like you just want to use the .Contains
method:
List<string> ImageFormats = new List<string>();
ImageFormats.Add("png");
ImageFormats.Add("jpg");
ImageFormats.Add("jpeg");
ImageFormats.Add("tiff");
ImageFormats.Add("gif");
var results = _database.Documents
.Where(d => ImageFormats.Contains(d.Extension))
.ToList();