4

我们有一个表单,允许用户通过在文本框中输入来过滤列表。我们需要根据两个字段过滤列表。FundName 和 CompanyName。当表单加载时,我将初始 LINQ to SQL 结果放入一个列表中,这样对于每个后续操作(过滤器),数据库都不会被命中。这显着加快了处理速度(从大约 400 毫秒到每个过滤器操作不到 6 毫秒,例如键入一个字符)并减少了 DB 喋喋不休。

问题是当我们决定对两个字段进行过滤条件搜索时,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()

任何和所有的帮助和建议将不胜感激。

4

1 回答 1

7

如果您收到 NullReferenceException,听起来 FundName 或 CompanyName 为 null(无)。尝试:

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

(语法可能有点偏离,但希望你能明白要点。)

于 2008-11-12T19:47:03.867 回答