Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to loop through a List of strings against a database value in C#

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

            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?

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading