VB.net Extract value from datatable

Murray Brown
Murray Brown used Ask the Experts™
on
Hi

I have a datatable that I need to extract a value from.
If I used SQL the query would be "Select WorkType From Employee Hours Where LineID = 12"

What VB.net code would I use to extract this value from a datatable called "dt".

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Using LINQ, you could do something like this:
Dim result = dt.Rows.Cast(Of DataRow).FirstOrDefault(Function(r) Equals(r("LineID"), 12))("WorkType")

Open in new window

Or
Dim result = (From row In dt.Rows.Cast(Of DataRow) Where Equals(row("LineID"), 12) Select row("WorkType")).FirstOrDefault()

Open in new window

Proof of concept -
Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Module Module1
    Sub Main()
        Dim dt = Enumerable.Range(1, 20).Select(Function(i) New With {.ID = i, .WorkType = $"WorkType{i}", .LineID = i}).ConvertToDataTable()
        Dim result = dt.Rows.Cast(Of DataRow).FirstOrDefault(Function(r) Equals(r("LineID"), 12))("WorkType")
        Console.WriteLine(result)
        Console.ReadLine()
    End Sub
End Module

Module Extensions
    <Extension>
    Public Function ConvertToDataTable(Of T)(ByVal source As IEnumerable(Of T)) As DataTable
        Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
        Dim table As DataTable = New DataTable()

        For i As Integer = 0 To properties.Count - 1
            Dim [property] As PropertyDescriptor = properties(i)
            If [property].PropertyType.IsGenericType AndAlso [property].PropertyType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then
                table.Columns.Add([property].Name, [property].PropertyType.GetGenericArguments()(0))
            Else
                table.Columns.Add([property].Name, [property].PropertyType)
            End If
        Next

        Dim values(properties.Count - 1) As Object
        For Each item As T In source
            For i As Integer = 0 To properties.Count - 1
                values(i) = properties(i).GetValue(item)
            Next
            table.Rows.Add(values)
        Next

        Return table
    End Function
End Module

Open in new window

Produces the following output -Capture.PNG-saige-
Murray BrownASP.net/VSTO Developer

Author

Commented:
Thanks very much

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial