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

C# Use LINQ to filter files based on separate given extension array

I am working on .NET CORE 6 solution. I have list of files along with each extension and another list of extensions i.e. .csv. I want to linq to filter files from list 1 based on list 2. i.e. if list 2 have .csv & .txt then LINQ should filter out only .csv and .txt files. I did implement solution but it is using loop

  private List<string> FilterFilesWithAcceptedExtenison(List<string> files, List<string> acceptedExtensions)
    {
        List<string> FilteredFiles = new List<string>();

        foreach(var file in files)
        {
            var extension = Path.GetExtension(file);

            if (acceptedExtensions.Contains(extension))
            {
                FilteredFiles.Add(file);
            }
        }

        return FilteredFiles;
    }

>Solution :

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

You can use .Where() clause to filter files based on given criteria. Like,

Filters a sequence of values based on a predicate.

using System.Linq;
using System.Collections.Generic;

...
List<string> FilteredFiles = files
     .Where(file => acceptedExtensions.Contains(Path.GetExtension(file))
     .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