tags:

views:

78

answers:

4

Hi 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!

+3  A: 

.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.

Russell Steen
There are more elegant ways (parsing out the date, etc.), but this should get it done.
Russell Steen
A: 

Hi Russell

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

Southsouth
You'll want to insert your own logic there. Write a method that takes a string and returns a bool of whether the path is valid, and call that in your lambda.
Tullo
Ah, too right. Sorry about that. I was focusing on the lambda more so than the string comparison.
Russell Steen
A: 
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.

Yuriy Faktorovich
+1  A: 

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)
    });
jscharf
Your query as written won't work, the Lambda doesn't return anything , you aren't escaping '\', and your first string isn't formatted the same. But the Compare should work
Yuriy Faktorovich
Whoops thanks. Edited for sloppiness.
jscharf