I am trying to convert this test code to C# and having a problem with the Trim command. Has anyone done anything similiar like this in C# going to use this with a text box for searching the 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
What is the issue you are having? And what LINQ provider is this? An in-memory set (LINQ-to-Objects)? Or LINQ-to-SQL? Or LINQ-to-Entities?
I suspect you are getting something about the db LINQ provider not knowing about Trim() – in which case, try doing the trim first:
This addresses
twothree separate issues:1: captures: in the original, it is
txtSearchthat is captured into the query, which has complications; by evaluating theTrimfirst, it issthat is captured, which is a simple immutable string2: expression complexity: with expression-based LINQ (i.e. to a database), the entire expression (including
.Text,.Trim, etc) is part of the expression. If the LINQ provider doesn’t recognise one or more of those, it will fail. By reducing it to a string first, all the LINQ provider needs to handle is a string, which every provider should be fine with.(added) 3: repeated computation: LINQ-to-Objects is very literal; if you ask it to use a complex operation in a Where (etc), it will, even if it is obvious that the answer is unchanged per row; i.e.
txtSearch.Text.Trim()shouldn’t change per row, so why evaluate it per row? Evaluate it before the query and it is only done once.