tags:

views:

802

answers:

3

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
A: 

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

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

Victor
+1  A: 

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:

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

This addresses two three separate issues:

1: captures: in the original, it is txtSearch that is captured into the query, which has complications; by evaluating the Trim first, it is s that is captured, which is a simple immutable string

2: 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.

Marc Gravell
A: 

I've come across this too when switching to C#. The intellisense is way worse in C# : <

Make sure you aren't leaving out the () after Trim.

Shawn Simon