vb.net 从没有 For Each 循环的 DataTable.Select 中获取第一个结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15756995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:04:31  来源:igfitidea点击:

Get First result from DataTable.Select without For Each loop

vb.net

提问by Jegan Nagarajan

The below For loop does not loop at all. Is there any optimized way to do the same without For loop:

下面的 For 循环根本不循环。在没有 For 循环的情况下,是否有任何优化的方法可以做到这一点:

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.

有没有其他优化的方法来改变这个根本不循环的 For 循环。

回答by MarcinJuraszek

Looks like you want get "ID"from first row in your DataTable without using For Eachloop. You can do that using LINQ FirstOrDefaultmethod - it returns first element of collection or default value (Nothingfor all reference types) it collection hasn't got results:

看起来您想"ID"在不使用For Each循环的情况下从 DataTable 的第一行获取。您可以使用 LINQFirstOrDefault方法来做到这一点- 它返回集合的第一个元素或默认值(Nothing对于所有引用类型),它的集合没有得到结果:

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.Linqat the top of your file to make it works.

您需要Imports System.Linq在文件的顶部才能使其正常工作。

Or without LINQ:

或者没有 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