Select with condition from a datatable in VB.net

12,904

You can use Linq-To-DataSet:

Dim matchingRows As IEnumerable(Of DataRow) = 
    From row In table
    Where row.Field(Of String)("error_case") = "condition"

If you just want one column (of course that works also in one step):

Dim errorMessages As IEnumerable(Of String) = 
    From row In matchingRows 
    Select row.Field(Of String)("error_message")

For Each error In errorMessages 
    Console.WriteLine(error)
Next 

If you expect it to be just a single row use First or Single(throws an exception if there is more than one row):

Dim error As String = errorMessages.First()

Since First throws an exception if the sequence is empty you can use FirstOrDefault:

Dim error As String = errorMessages.FirstOrDefault() ' is null/Nothing in case of an empty sequence 

All in one line (note that both Linq and DataTable.Select needs to use loops):

Dim ErrMessage As String = errorTable.AsEnumerable().
    Where(Function(r) r.Field(Of String)("Error_Case") = TextCase.Text).
    Select(Function(r) r.Field(Of String)("Error_Message")).
    FirstOrDefault()
Share:
12,904
HelpASisterOut
Author by

HelpASisterOut

Program-err.

Updated on June 04, 2022

Comments

  • HelpASisterOut
    HelpASisterOut almost 2 years

    I want to select a certain field from a datatable in VB based on the value of another field in the same row.

    In SQL, it would easily be done by writing this query:

    select error_message from table_errors where error_case="condition"
    

    How do I do this if I have my SQL table filled in a datatable in VB? How do I select the item("error_message") in the datatable based on the item("error_Case") field?

    Any help would be appreciated