Reputation: 2551
I have the below datatable, how can I sort the datatable by Today name, so for example if today is Monday, it should show at the end of the Datatable
I tried the following, but it is not working
Dim dv As DataView = dt3.DefaultView
dv.Sort = " DayLog desc"
Dim sortedDT = dv.ToTable()
Upvotes: 0
Views: 385
Reputation: 817
Been some time since I've done some VB, surely you could do the following?
Dim data() AS DataRow = dt.Select()
Dim sortedData = data.OrderBy(Function(x) CInt([Enum].Parse(GetType(DayOfWeek), x.Item("DayLog"))) )
Dim sortedDataTable = dt.Clone()
For Each row In sortedData
sortedDataTable.ImportRow(row)
Next
Assuming the spelling of your days of the week is 100% correct
If you have the string value of the current day of the week or you know the int value, then you can adjust the sort using modulus
eg.
Dim todayStringVal = "Tuesday" // say you have this value from somewhere
Dim today = CInt([Enum].Parse(GetType(DayOfWeek), todayStringVal)) // convert to day of the week enum
Dim sortedData = data.OrderBy(Function(x) CInt(([Enum].Parse(GetType(DayOfWeek), x.Item("DayLog")) + 7 - today)) Mod 7) // Apply sorting
Finally if you want the above snippet to sort so that today
's value is at the end of the list just change OrderBy
to OrderByDescending
EDIT
To ensure today
's value appears first in your list even though DayOfWeek
's index starts at 0 you need to + 7 and subtract the index then mod by 7 to get the correct index to sort by
eg. Saturday's index on the DayOfWeek
enum is 6 therefore 6 + 7 (Days of the week) = 13 then subtract by 6 = 7 finally 7 mod 7 is 0, so Saturday's new index becomes 0 and gets ordered first in the list
Upvotes: 1