zeencat
zeencat

Reputation: 590

Best way of filtering a list using linq?

I'm a little confussed as to whether or not this is the best method to retrieve what I need. I've got a list of files I've gotten from a directory using ftp. I need to filter the list of file names depending on the file mask entered by the user into a List<string>. I love LINQ, but not having used it for a few months I seem to have lost some of my skills already. I've come up with the following so far. I would be greatful if someone could verify what I've done is the best approach.

foreach (string s in fileMasks)
{
    fileNames.AddRange(
        directory.Files.ToList().Where(a => a.Name.EndsWith(s))
        .Select(b => b.Name)
    );
}

Upvotes: 0

Views: 570

Answers (4)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47048

It seems OK, but you can skip the .ToList() in the middle.

You could also rewrite with query syntax

fileNames.AddRange(
    from file in directory.Files
    where file.Name.EndsWith
    select file.Name
);

I often find the query syntax more easy to read.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You don't need any foreach loops and AddRange, you could use the SelectMany extension method:

List<string> result = directory
    .Files
    .SelectMany(f => fileMasks.Where(m => f.Name.EndsWith(m)), (f, m) => f.Name)
    .ToList();

or if you prefer the using the LINQ syntax:

List<string> result =
    (from f in directory.GetFiles()
    from m in fileMasks
    where f.Name.EndsWith(m)
    select f.Name).ToList();

That's LINQ. But since you are dealing with filtering directories you could use file masks. The DirectoryInfo.GetFiles method allow you to do this.

Upvotes: 1

Vitalii Ivanov
Vitalii Ivanov

Reputation: 3251

Solution without foreach statement

fileNames.AddRange(
    (from file in directory.Files
    from m in fileMasks
    where file.Name.EndsWith(m)
    select file.Name)); 

Upvotes: 0

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

you could just simplify your query

fileNames.AddRange(directory.Files.Select(f => f.Name).Where(a => a.EndsWith(s));

Upvotes: 2

Related Questions