开发者

Linq vb.net: Find Item in DataRow[]

gefundeneID = drTerminal.AsEnumerable().Single(Function(s) s("TerminalID") = RandomID)

Have an array of DataRow and want to look if the RandomID is in one of the rows.

What's wrong with this code?

EDIT: Got 开发者_开发知识库this error: The operator = isn't defined for DBNull and Integer


Apparently, your code has trouble comparing TerminalID, which can be DBNull, with the integer RandomID. You can avoid this problem by accessing TerminalID as follows:

...(Function(s) s.Field(Of Integer?)("TerminalID") = RandomID)

DataRow.Field provides strongly typed access to data fields, and, when used with nullable types (such as Integer?), automatically converts DBNulls to Nothing. Since Integer? (your field) and Integer (RandomID) can be compared with =, the above code should work fine.

As a side comment: I would recommend to turn on Option Strict, this avoids using a lot of implicit conversions all over the place and encourages good coding style. (Yes, you will get a lot of compile errors after turning it on, but it's for a good cause... for improving the quality of your code. With Option Strict On, your code example would not even have compiled.)


If you want to check to see if the ID is in your set, don't use Single as that will throw an exception if no match is found. If you only want to return true or false if the match is found, use .Any. If you want to return the found result, consider SingleOrDefault (if you know that there can only be 0-1 matches) or FirstOrDefault if you potentially can return multiple matches.

@Heinzi's comments regarding field nullability and Option Strict are worth considering as well.


try the following function:

Private Function ItemAdded(UserID As String) As Boolean
        Return (tbl.Select(String.Format("UserID ='{0}'", UserID)).Count > 0)
End Function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜