"Any religion...is for ever in danger of petrifaction into mere ritual and habit, though ritual and habit be essential to religion." - T. S. Eliot

Linq is the new data query tool available in Visual Studio 2008 (VB 9). VS2008 is capable of targeting either .NET 2.0 or 3.5. Linq is only available if you target version 3.5.

Dim AllFiles As New List(Of IO.FileInfo)

Dim di As New IO.DirectoryInfo("c:\my\directory\name") If di.Exists Then AllFiles.AddRange(di.GetFiles("*.*", IO.SearchOption.AllDirectories)) End If

Dim filequery = From fi In AllFiles _ Where fi.LastWriteTime >= Date.Now.AddDays(-7) _ And fi.Length > 100000 _ Order By fi.Extension, fi.Name Descending _ Select fi.DirectoryName, fi.Name

For Each itm In filequery Console.WriteLine(itm.Name & " = " & itm.DirectoryName) Next

Things of note:

  • Use a List(Of FileInfo) instead of an array. That way, if the directory doesn't exist, the object still has an instance, just no files.
  • If one of your WHERE clause elements is going to be the file's extension and you don't need the other files for later queries, change the first parameter to the GetFiles method to limit the amount of memory you use.
  • You must have Option Infer turned on. FileQuery and Itm both use anonymous types.
  • The FileQuery object is compatible with data source binding and can be used as a grid's data source directly.

While you can have more than one condition in the initial query, you can also add additional where clauses on the fly:

Dim filequery = From fi In AllFiles _
                Where fi.LastWriteTime >= Date.Now.AddDays(-7) _
                Order By fi.Extension, fi.Name Descending _
                Select fi.DirectoryName, fi.Name, fi.Length

If JustLargeFiles = True Then filequery = From fi In filequery _ Where fi.Length > 100000 End If

Notice that the add-on query doesn't have a SELECT clause. This guarantees the type returned by both queries is the same so you don't need to generate more than one query variable. Also important is that fi.Length is part of the first query's SELECT clause or else the add-on query won't be able to reference it.

ScrewTurn Wiki version 2.0.33. Current Page Count: 23. Some of the icons created by FamFamFam.