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

Time:05-10

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

CodePudding user response:

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();

CodePudding user response:

its simply

var filteredFiles = files.Where(f => acceptedExtensions.Contains(Path.GetExtension(f)));

You can throw a ToList() on the end if you really need it to be a List<string>.

  • Related