VB.net code to filter a datatable

Rajnilari2015
Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 2444
Let's say we have a DataTable in which their is a column of age. We need to select the person whose age is the older one. The below code will do

Public Function GetData() As DataTable


Dim dt As New DataTable()

'Add some columns

dt.Columns.Add(New DataColumn("Age", GetType(Int32)))

'Add some rows

'First Row

Dim row1 As DataRow = dt.NewRow()

row1("Age") = 21

'Second Row

Dim row2 As DataRow = dt.NewRow()

row2("Age") = 11

'Third Row

Dim row3 As DataRow = dt.NewRow()

row3("Age") = 12

'Fourth Row

Dim row4 As DataRow = dt.NewRow()

row4("Age") = 55

'Fifth Row

Dim row5 As DataRow = dt.NewRow()

row5("Age") = 18



'Add the rows to the table

dt.Rows.Add(row1)

dt.Rows.Add(row2)

dt.Rows.Add(row3)

dt.Rows.Add(row4)

dt.Rows.Add(row5)

'return the table

Return dt

End Function



Then filter as under

Dim oldestRecord = GetData().AsEnumerable().[Select](Function(dr) dr("Age")).Max()

Comments or Responses

Login to post response