Southsouth
Southsouth

Reputation: 2695

Linq to filter directories

I get the followwing direcories by calling GetDirectories()

c:\app\20090331\ c:\app\20090430\ c:\app\20090531\ c:\app\20090630\ c:\app\20090731\ c:\app\20090831\

I want to the directories between 20090531 and 20090731, How can I do it by Linq? Thanks!

Upvotes: 2

Views: 176

Answers (4)

jscharf
jscharf

Reputation: 5899

Use a LINQ .Where statement and String.Compare between your min and max directory names (as strings) with x (as a string).

Don't bother using blah .Parse, just do string comparisions - your directory names are numerical anyways so there's no use parsing each when you can just use a straight value comparison anyways.

var query = directories
    .Where(x => {
        return (String.Compare(x, @"c:\app\20090531") > 0 && String.Compare(x, @"c:\app\20090731") < 0)
    });

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

var query = directories
    .Where(d => {
        int directoryNumber = int.Parse(d.Replace(@"c:\app\", string.Empty)
            .Replace("\\", string.Empty));
        return directoryNumber > 20090531 && directoryNumber < 20090731;
    });

You can also convert it to DateTime if necessary.

Edit: apparently stackoverflow, or whatever parsing it uses doesn't like my verbatim strings.

Upvotes: 0

Southsouth
Southsouth

Reputation: 2695

I got: operator '>' cannot be applied to operands type of 'string' and 'string'

Upvotes: 0

Russell Steen
Russell Steen

Reputation: 6612

.Where(x => x > "c:\app\20090531" && x < "c:\app\20090731").ToList()

The tolist is if you want it in a list. Leave that off if you are fine with IEnumerable.

Upvotes: 3

Related Questions