简体   繁体   中英

VB.Net Select from Datatable: Order by Field 1, OR by Field 2 if Field 1 is null?

I have this Select in VB.Net:

Dim thisMonthQuery =
    From email In DataTablePickers.AsEnumerable() _
    Where (email.Field(Of DateTime?)("GenDateScheduled") IsNot Nothing _
            AndAlso email.Field(Of DateTime?)("GenDateScheduled") >= New DateTime(curYear, curMonth, 1)) _
    Or (email.Field(Of DateTime?)("GenDateCreated") IsNot Nothing _
        AndAlso email.Field(Of DateTime?)("GenDateCreated") >= New DateTime(curYear, curMonth, 1)) _
    Select email

I need to order the results by date. However, I have two date fields, and the one that I want to order by may be NULL. I want to order by GenDateScheduled, but if GenDateScheduled is NULL, I want to order by GenDateCreated. Something like this:

Order By (email.Field(Of DateTime)("GenDateScheduled") IsNot Nothing ? email.Field(Of DateTime)("GenDateScheduled") : email.Field(Of DateTime)("GenDateCreated"))

but that line doesn't work, it's not valid VB.Net code. How do I accomplish this?

What you're describing is an "order by, then by" approach. In LINQ I believe it's accomplished with a simple comma-separated list of order fields:

Order By email.Field(Of DateTime)("GenDateScheduled"), email.Field(Of DateTime)("GenDateCreated")

After all, consider what "might be NULL" logically means. Some records might be NULL. But you don't sort an individual record , you sort the entire set of records. So some might have a NULL value in that field, some might not. Thus, if you order by that field, then all of the NULL values will be in the same location in the sort.

To sort the records in that location (and in any other location where multiple records have the same sorted value), simply order by another value. Which is the second column used in the sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM