How can I obtain a directory's file list sorted by timestamp? - vb.net

I am stuck on this sorting problem.
Private Sub ...
Dim oDirInfo As DirectoryInfo
Dim aoFSInfo() As FileSystemInfo
Dim asFiles() As String
FQPN is a fully qualified path name ending in "\*.*".
oDirInfo = New DirectoryInfo(FQPN)
Now into asFiles I want the files' names, sorted by the files' timestamps in ascending order. I presume, that oDirInfo.CreationTime plays a role here, but can not figure out how to use OrderBy properly.
aoFSInfo = oDirInfo.GetFileSystemInfos() '?
asFiles = aoFSInfo.OrderBy(...)
End Sub

Yes, that's LINQ and you can use this (method-)syntax:
asFiles = oFSInfo.
OrderBy(Function(fsi) fsi.CreationTime).
Select(Function(fsi) fsi.FullName).
ToArray()
If you don't like the ugly Function keyword you can use query syntax:
Dim orderedFiles = From fsi In oFSInfo
Order by fsi.iCreationTime Ascending
Select fsi.FullName
asFiles = orderedFiles.ToArray()
Even if these are two statements it's not slower than method syntax due to deferred execution.

Related

Equals() function with multiple values instead of one

I have been using the following since a few years:
Dim mycol = xml.First(Function(x) CStr(x.Attribute("name")).Equals("Source"))
Now I would like to retrieve if either the name attribute is equal to "Source" or "Input".
Does any solution exist for this case?
I have tried the following without any success
Dim cases As String() = {"Source", "Input"}
Dim mycol = xml.First(Function(x) CStr(x.Attribute("name")).Equals(cases))
You would reverse the order of the comparison and use Contains:
Dim mycol = xml.First(Function(x) cases.Contains(CStr(x.Attribute("name"))))

Error when using linq on datatable

I am trying to run the following code converting my datatable to be usable in linq all seems fines and compiles but when I Execute the statement I get the following statement i get the error below new entires just has location and ordernumber in the return values I have to do it this way as I am supporting a legacy access 97 system thanks.
Dim total = From row In newEntries.AsEnumerable()
Select row.Field(Of Int32)("location") Distinct
retVal = Convert.ToInt32(total)
This is my whole code but im still getting an invalid type cast error their is data exsits for this order by teh way
Dim retVal As Int32
Dim newEntries As New DataTable
Dim script As String = scriptBuilder.GetDistinctOrdersForLocations(OrderNumber)
newEntries = connection.SqlSelectToDataTable(script)
Dim total = From row In newEntries.AsEnumerable()
Select row.Field(Of Int32)("location") Distinct
retVal = total.Count()
If you want the count of the collection just do this:
retVal = total.Count()
this will return the count from the distinct query that you have written.
Just to clarify, #David B identified the data type of location was int16 not int32, so changing this in the linq query resolved the issue.
Your LINQ query is returning a collection. You should use something like First or FirstOrDefault.
I'm a little rusty on VB LINQ, but try :
retVal = Convert.ToInt32(total.First())
Note: This will throw an error if there are no items in the collection.
It's important to understand when you write a LINQ query and assign it to a variable, that variable essentially contains a query object, and not the results of running the query. In order to get the value that results from the query, you need to call some method on the query object such as:
total.Single() ' Assumes you expect the query to return exactly one result.
I changed the code to int16 worked here is the code for any one else stuck thanks #Ric
Dim retVal As Int32
Dim newEntries As New DataTable
Dim script As String = scriptBuilder.GetDistinctOrdersForLocations(OrderNumber)
newEntries = connection.SqlSelectToDataTable(script)
Dim total = From row In newEntries.AsEnumerable()
Select row.Field(Of Int16)("location") Distinct
retVal = total.Count()

DataTable.Select.Where VB.Net - Delete rows

I'm currently pulling information using a query that I'm not allowed to tamper with:
Dim dt As DataTable = BLL.GetData(variable).Tables(0)
Immediately afterwards, I'm removing any records where a field begins with a specific value:
For Each dr As DataRow In dt.Rows
If dr.Item(2).ToString().StartsWith("value") Then
dr.Delete()
End If
Next
What I'd really like to do is something like:
dt.Select.Where(field1 => field1.StartsWith("value")).Delete()
I know that is not the syntax of it and I'm probably very off from what it would be like. The For Each works fine, I'm just trying to "simplify" it. Any idea? Any and all help is appreciated.
Actually, your initial code is probably the cleanest and most straight forward.
To delete items using LINQ, you first need to read them into a separate collection, then loop through that collection and call Delete on each record. If you'd rather go that route, you could try:
Dim records = dt.Rows.Where(Function(r) r.StartsWith("value")).ToList()
For Each r In records
r.Delete()
Next
The answer I think you are looking for is below from Microsoft. https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
Dim table As DataTable = DataSet1.Tables("Orders")
' Presuming the DataTable has a column named Date.
Dim expression As String
expression = "Date > #1/1/00#"
Dim foundRows() As DataRow
' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)
Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
Console.WriteLine(foundRows(i)(0))
Next i

DataTable Select(String) Function Help VB .NET

I made a datatable with 2 columns a transactionTime column and a numberOfTransactions column. I made the table with the pre-defined transaction times and want to add the number of transactions from an XML file. I have gotten through the XML file and want to add the data to the correct row. Here is the function:
Function AddRow(ByVal timeOfTransaction As String, ByVal numberOfTransactions As String, ByRef dataTableOfTransactions As DataTable) As String
Dim row() As DataRow = dataTableOfTransactions.Select("transactionTime = timeOfTransaction")
If row(0) IsNot Nothing Then
row(0)("numberOfTransactions") = numberOfTransactions
End If
Return Nothing
End Function
When I run this it overwrites the first element in the table's numberOfTransactions coloumn. I know it has to do with the "transactionTime = timeOfTransaction" part but I can't seem to get it to read timeOfTransaction as a reference to a string instead of a literal. Any help would be much appreciated. Thanks!
You need to write something like this :
Dim row() As DataRow = dataTableOfTransactions.Select("transactionTime=#" & timeOfTransaction & "#")
But be careful with your date/month or month/date format, it depends of your regional settings.
row(0)("numberOfTransactions") = numberOfTransactions
Right there you are telling the program to overwrite that value with number of transactions.
If you want that value you need to set it to something, not set something to it.
Also, if you want your select to work properly try doing it like this
dataTableOfTransactions.Select("transactionTime = " + timeOfTransaction)

Sorting numbers in descending order

I have 20 textboxes. each contains a particular number . I want the textbox1 to textboxN to have the numbers in the descending order. If any of the textbox has a zero value then I want to leave that textbox as it is. A sample code in vb.net needed.
'for sorting the elements in descending order
dim array(4) as integer
array(4)={4,6,2,9,1}
'first sort the array and then reverse it as
array.sort(4)
array.reverse(4)
sortlistbox.item.add(array(4))
Dim txt As New List(Of TextBox)
Dim q = From i In txt
Where CInt(i.Attributes("value")) > 0
Order By CInt(i.Attributes("value")) Descending
Select i
Whana try some simple linq query over your collection?
This one is a bit old, but I ran into the same problem.
Using MSDN I found this: Enumerable.OrderBy Method (IEnumerable, Func)
If you just add .Reverse to that query, it's descending:
Dim query As IEnumerable(Of Pet) = pets.OrderBy(Function(pet) pet.Age).Reverse
#Thom Morgan
This one is a bit old, but I ran into the same problem.
Using MSDN I found this: Enumerable.OrderBy Method (IEnumerable, Func)
If you just add .Reverse to that query, it's descending:
Dim query As IEnumerable(Of Pet) = pets.OrderBy(Function(pet) pet.Age).Reverse
This worked like a charm! Thank you!