user7956567
user7956567

Reputation: 25

Directory.EnumerateFiles with Take and Where

I have following Problem:

For Each _file As String In Directory.EnumerateFiles(Quellpfad, "*.rdy").Take(500).Where(Function(item) item.Replace(Quellpfad, "").Length <= 11)

this code should take files from a Directory saved in the String "Quellpfad" by These 2 criteria:

1.) only 500 files

2.) filename lenth <= 11 eg.: 0330829.rdy

The file 0330829.rdy is in the Directory but I can't find it with the code above.

Upvotes: 1

Views: 415

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You should use Take last because you want to apply the filter first, you should also use Path.GetFileName or Path.GetFileNameWithoutExtension instead of String.Replace:

Dim files = From file In Directory.EnumerateFiles(Quellpfad, "*.rdy")
            Where Path.GetFileName(file).Length <= 11
            Take 500 

In VB.NET query syntax supports Take, so i'd prefer that.

Upvotes: 2

A Friend
A Friend

Reputation: 2750

You need to reorder your statement to put the Where before the Take:

For Each _file As String In Directory.EnumerateFiles(Quellpfad, "*.rdy").Where(Function(item) item.Replace(Quellpfad, "").Length <= 11).Take(500)

The Where returns all files matching your condition FIRST, and THEN limits those down to 500.

Upvotes: 1

Related Questions