Using LINQ with a DataTable

RogerSchlueter-7899 1,301 Reputation points
2024-07-07T14:06:04.1433333+00:00

Consider this Datatable:

With tbl
	    .Columns.Add("Beginning", GetType(Date))
        .Columns.Add("Title", GetType(String))
		.....
    End With

This LINQ extracts all items with a "Beginning" date greater than the current date:


    From evnt In dtEvents.AsEnumerable
    Where evnt.Field(Of Date)("Beginning") > Date.Now.Date
    Order By evnt.Field(Of Date)("Beginning")
    Select (evnt.Field(Of Date)("Beginning").ToString("MMM d"), evnt.Field(Of String)("Title"))

This works but has two issues:

  1. I want to sort "Beginning" in descending order but can't figure out how.
  2. I cannot get the Select clause to produce what I want. Here is one line of output as an example of what I want: Sep 2, Labor Day

The Select clause shown above gives (the parens are necessary to avoid an error):

(Sep 2, Labor Day)

Using:

vb
Select D = evnt.Field(Of Date)("Beginning").ToString("MMM d"), E = evnt.Field(Of String)("Title")

gives

D = Sep 2, E = Labor Day

How can achieve the desired result?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,725 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 31,321 Reputation points Microsoft Vendor
    2024-07-08T01:37:46.75+00:00

    Hi @RogerSchlueter-7899 ,

    You can sort the Beginning date in descending order by using Order By ... Descending.

    Concatenate the fields in the Select clause to achieve the desired output format without adding extra characters like parentheses or the D =, E = format.

    Dim result = From evnt In dtEvents.AsEnumerable
                 Where evnt.Field(Of Date)("Beginning") > Date.Now.Date
                 Order By evnt.Field(Of Date)("Beginning") Descending
                 Select evnt.Field(Of Date)("Beginning").ToString("MMM d") & ", " & evnt.Field(Of String)("Title")
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.