Get First result from DataTable.Select without For Each loop
vb.net
Solution
Looks like you want get `"ID"` from first row in your DataTable without using `For Each` loop. You can do that using LINQ `FirstOrDefault` method - it returns first element of collection or default value (`Nothing` for all reference types) it collection hasn't got results:
Dim firstRow As DataRow = dttable.Select("ID=1 and FirstName='Karthik'", "ID").FirstOrDefault()
If Not firstRow Is Nothing Then
NewID = CInt(firstRow.Item("ID"))
Else
NewID = 0
End If
You need `Imports System.Linq` at the top of your file to make it works.
Or without LINQ:
Dim results As DataRow() = dttable.Select("ID=1 and FirstName='Karthik'", "ID")
If results.Length > 0 Then
NewID = CInt(results(0).Item("ID"))
Else
NewID = 0
End If
Problem
The below For loop does not loop at all. Is there any optimized way to do the same without For loop: ``` For Each drID As DataRow In dttable.Select("ID=1 and FirstName='Karthik'", "ID") NewID = CInt(drID.Item("ID")) Exit For Next ``` I have tried changing this with ``` NewID = IIf(dt.Select("ID=1 and FirstName='Karthik'", "ID").Length > 0, dt.Select("ID=1 and FirstName='Karthik'", "ID")(0).Item("ID"), 0) ``` Is there any other optimized way to change this For loop which does not even loop at all.