Using Linq and Trim.Text for Search

I am trying to convert this test code to C # and have a problem with the Trim command. Has anyone done something like this in C # to use this with a search textbox in an aspx page.

Dim q = From b In db.Blogs _
        Where b.BlogContents.Contains(txtSearch.Text.Trim()) Or _
              b.BlogTitle.Contains(txtSearch.Text.Trim()) _
        Select b

      

+1


source to share


3 answers


What is the problem? And which LINQ provider is it? In-memory collection (LINQ-to-Objects)? Or LINQ-to-SQL? Or LINQ-to-Entities?

I suspect you are getting something about the LINQ db provider without knowing about Trim () - in that case, try trimming first:

string s = txtSearch.Text.Trim();
var q = from b in db.Blogs
        where b.BlogContents.Contains(s) || b.BlogTitle.Contains(s)
        select b;

      

There are two three separate questions in this address :



1: captures: the txtSearch

request is recorded in the source text , which has difficulties; evaluating first Trim

, it is captured s

, which is a simple immutable string

2: Expression Complexity: With LINQ based on expressions (eg in a database), the entire expression (including .Text

, .Trim

etc.) is part of the expression. If the LINQ provider does not recognize one or more of them, it will fail. Bringing it down to a string first, all the LINQ operator has to handle is a string that needs to be fine with every provider.

(added) 3: re-computation: LINQ-to-Objects are very literal; if you ask him to use a complex operation in Where (etc.), it will be, even if it is obvious that the answer does not change in the line; those. txtSearch.Text.Trim()

shouldn't be changed for every line, so why evaluate it per line? Evaluate it before asking and it only gets executed once.

+2


source


not sure what you are asking, but the Trim function in C # is the same.



http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx

0


source


I also ran into this when switching to C #. Intellisense is much worse in C #: <

Make sure you don't leave ()

after pruning.

0


source







All Articles