我们有一个表单,允许用户通过键入文本框来过滤列表.我们需要根据两个字段过滤列表.FundName和CompanyName.当表单加载时,我将初始LINQ to SQL结果放入一个列表中,以便对于每个后续操作(过滤器)都不会命中数据库.这会显着加快速度(从每个过滤器操作大约400毫秒到不到6毫秒,比如键入字符)并减少数据库抖动.
问题是,当我们决定在两个字段上搜索过滤条件时,LINQ to Object查询不起作用.我可以有一个具有多个条件的查询,而不是多个LIKE(或.Contains或.Endswith等方法,这些方法评估为SQL LIKE语句).该查询确实对LINQtoSQL起作用,而不是针对该对象.以下是一些示例代码:
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
例外情况是"对象引用未设置为对象的实例". - 堆栈跟踪是:
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()
任何和所有的帮助和建议将不胜感激.
如果您收到NullReferenceException,则听起来像FundName或CompanyName为null(Nothing).尝试:
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
(语法可能有点偏,但希望你得到要点.)