开发者

LINQ .Startswith or .Contains problems in VB.NET4

This may be a newbie question...

开发者_开发百科

In my code I can easily use "where Obj.Feld = String", but using "where Obj.Feld.StartsWith("a")" doesn't work. See the following two functions:

    Public Function EntriesByFileName(ByRef Database() As Entry, ByVal Filename As _
  String) As IEnumerable(Of Entry)
        Dim Result As IEnumerable(Of Entry) = From EntryObject In Database _
        Where (EntryObject.FileName = Filename) Select EntryObject
        Return Result
    End Function

    Public Function EntriesLikeFileName(ByRef Database() As Entry, ByVal _
      Filename As String) As IEnumerable(Of Entry)
        Filename = Filename.ToLower
        Dim Result As IEnumerable(Of Entry) = From EntryObject In Database _
          Where EntryObject.FileName.StartsWith("a") Select EntryObject
        Return Result
    End Function

The first function (byFileName) works fine. The second function (LikeFileName) doesn't. Using Startswith I get "Object reference not set to an instance of an object." What am I doing wrong?

Database is an array of Objects, a structure consisting of strings


EntryObject.FileName can be NULL, so EntryObject.FileName.StartsWith(..) can throw a NullReferenceException.

Change the condition to first check for NULL eg

if EntryObject.FileName <> nothing AndAlso EntryObject.FileName.StartsWith(..) 

Using AndAlso here employs short-circuiting, which means that if the first condition is not met, the second won't be evaluated and hence we can't get the NullReferenceException.


Make sure Database does not contain any null entries. You can apply the = operator on null, but you cannot call any methods on it, so StartsWith() fails.


looks like one of the EntryObject object has FileName property set to null. In first method it won't be detected because you can compare a null value to other value, but in second method, you are trying to invoke a method on a null object which will throw exception.


If you are using linq to entities then I don't think it supports startswith or contains. See this post Stackoverflow post

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜