How do I append a 'where' clause using VB.NET and LINQ?

前端 未结 5 1360
别跟我提以往
别跟我提以往 2020-12-16 10:28

I am pretty new to VB.NET and am having a bit of trouble here with something I thought should be simple.

Keeping it simple, let\'s say I have a Document table with \

5条回答
  •  孤街浪徒
    2020-12-16 11:05

    In LINQ to SQL you can add WHERE clauses to your query using the .Where method of the query object, as you noted in your question. To use the LIKE operator, try using the .Contains method of the object you're querying in the Lambda expression of your call to the Where method.

    Here's a simplified example in a console application. Hopefully it will lead you in the correct direction.

    Public Class Doc
    
        Private _docName As String
        Public Property DocName() As String
            Get
                Return _docName
            End Get
            Set(ByVal value As String)
                _docName = value
            End Set
        End Property
    
        Public Sub New(ByVal newDocName As String)
            _docName = newDocName
        End Sub
    End Class
    
    Sub Main()
        Dim Documents As New List(Of Doc)
        Documents.Add(New Doc("ABC"))
        Documents.Add(New Doc("DEF"))
        Documents.Add(New Doc("GHI"))
        Documents.Add(New Doc("ABC DEF"))
        Documents.Add(New Doc("DEF GHI"))
        Documents.Add(New Doc("GHI LMN"))
    
        Dim qry = From docs In Documents
    
        qry = qry.Where(Function(d) d.DocName.Contains("GHI"))
    
        Dim qryResults As List(Of Doc) = qry.ToList()
    
        For Each d As Doc In qryResults
            Console.WriteLine(d.DocName)
        Next
    
    End Sub
    

    Note the .Contains("GHI") call in the Lambda expression of the .Where method. I'm referencing the parameter of the expression, "d", which exposes the DocName property, which further exposes the .Contains method. This should produce the LIKE query you're expecting.

    This method is additive, i.e. the call to the .Where method could be enclosed in a loop to make additional LIKE operators added to the WHERE clause of your query.

提交回复
热议问题