Search code examples
c#listsearchoptimizationfindall

How to most efficiently get all filenames in a list that end with extensions matching those in a predefined array?


Specifically, I have a list of files and an array of compressed file extensions - I am trying to get all the zip files in a folder for later processing. I reviewed a couple other StackOverflow answers but they all involved having a series of "Contains" statements separates by or statements. What if I want to add a new extension during runtime? That just wasn't going to work for me.

string[] zipExts = new string[] { "zip", "tar.gz", "rar", "jar", "iso" };

// PseudoCode : Get a list of files
files = getfiles()

// Existing StackOverflow answers - their suggested way of doing things
var zips = files.FindAll(f => f.ToLower().Contains(zipExts[0].ToLower()) ||
    f.ToLower().Contains(zipExts[1].ToLower()) || 
    f.ToLower().Contains(zipExts[2].ToLower()) || 
    f.ToLower().Contains(zipExts[3].ToLower()) || 
    f.ToLower().Contains(zipExts[4].ToLower()));

What is the more efficient way to do this that doesn't require a series of or statements or a loop?

My own answer (the one I found myself then decided to document because I couldn't find it on StackOverflow) is an even cleaner version than the one to the question I am duplicating, because I knew there was a more concise way to do it (just didn't know how), so I didn't accept the other answers.


Solution

  • I figured it out after a bit of thinking.

    var zips = files.FindAll(f => zipExts.Any(z => f.EndsWith(z));
    

    Wasn't able to answer my post while posting it (didn't see the button, stupidly assumed I just had to answer after posting my question), to document the knowledge (I found the answer before I started asking this question).