0

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?

codeninja
  • 315
  • 2
  • 10

1 Answers1

3

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();
Daevin
  • 778
  • 3
  • 14
  • 31
  • @codeninja Don't forget to mark this as the answer then, by pressing the checkmark button. – Daevin Sep 08 '22 at 14:30
  • 1
    If you are using that LINQ on an `IQueryable` connected to TSQL backend, that should get composed into something like `WHERE [Extension] IN ('png', 'jpg', 'jpeg', 'tiff', 'gif')` – Jodrell Sep 08 '22 at 14:37
  • I ddnt know this was possible without using so many OR's – codeninja Sep 09 '22 at 06:02