LINQ to Objects: is a query possible with several LIKE conditions (OR or AND)?

We have a form that allows the user to filter the list by entering a text field. We need to filter the list based on two fields. Fund name and company_name. When the form loads, I put the original LINQ results in SQL in a list so that for each subsequent action (filter) the database does not fall. This significantly speeds up the work (from about 400 milliseconds to less than 6 milliseconds per filter action, for example, entering characters) and reduces database chatter.

The problem is that when we decided to search for filter criteria in two fields, the LINQ to Object query did not work. I can have a query with several criteria, but not a few LIKE methods (or .Contains or .Endswith, etc., that evaluate LIKE SQL queries). The query works against LINQtoSQL, not against the object. Here is a sample code:

Dim db As New BenchmarkLINQtoSQLDataContext() Dim fundList = From FundShort In db.FundShorts _ Select FundShort _ Order By FundShort.IRBB Dim linqFundShortList As New List(Of FundShort) linqFundShortList = fundList.ToList() Dim filterText = "aka" 'This works Dim successQuery = From fs In fundList _ Where fs.FundName.ToLower.Contains(filterText) _ Or fs.CompanyName.ToLower.Contains(filterText) _ Select fs FundBindingSource.DataSource = successQuery 'This also works Dim successQuery2 = From fs In linqFundShortList _ Where fs.FundName.ToLower.Contains(filterText) _ Select fs FundBindingSource.DataSource = successQuery2 'This does not Dim failQuery = From fs In linqFundShortList _ Where (fs.FundName.ToLower.Contains(filterText) _ Or fs.CompanyName.ToLower.Contains(filterText)) _ Select fs FundBindingSource.DataSource = failQuery 

The exception is "Link to an object not installed on an instance of the object." - stack trace:

  at Benchmark.BPRMS.FundsMain._Closure$__1._Lambda$__3(FundShort fs) in C:\Projects\BPRMS\Trunk\BPRMS\Forms\FundsMain.vb:line 72 at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext() at System.Linq.SystemCore_EnumerableDebugView`1.get_Items() 

Any help and suggestions are welcome.

+4
source share
1 answer

If you get a NullReferenceException, it looks like either FundName or CompanyName is null (Nothing). Try:

 Dim failQuery = From fs In linqFundShortList _ Where (((Not fs.FundName Is Nothing) AndAlso fs.FundName.ToLower.Contains(Me.filterText))_ OrElse ((Not fs.CompanyName Is Nothing) AndAlso fs.CompanyName.ToLower.Contains(Me.filterText))) _ Select fs 

(The syntax may be a bit off, but hopefully you get the gist.)

+7
source

All Articles