tags:

views:

106

answers:

4

Hi fellow coders

I'm new at LINQ, searching the net for LINQ samples that mimic SQL's LIKE statement doesn't satisfy myself.

What I want is producing the same query result as this SQL

SELECT * FROM table_1 WHERE column_1 LIKE '__0%'

I want to query from table_1 where column_1's third character is '0'

Is there equivalent statement in LINQ

:D thank you

A: 

Try this (I can't test it right now):

from t in table_1
where t.column_1[2] == '0'
select t;
Marcelo Cantos
@Marcelo: Probably because the code doesn't work as the underscore has a special meaning when used with `like`, but not when used with `StartsWith`.
Guffa
Doesn't this check if the entry starts with "__0" instead of if the third character is a "0"?
Jens
`_` means any character in a `LIKE` statement, whereas it has no special meaning to `StartsWith`.
Kent Boogaart
D'oh! Those underscores get me every time!
Marcelo Cantos
+5  A: 

Likes are produced by following methods: StartsWith, EndsWith and Contains. Try to play with them.

Andrey
He needs only the third character to be zero, so I guess he should look at `Substring` too.
Alex Bagnolini
A: 

In your exact case (assuming column_1 is a string):

from t in table_1
where !String.IsNullOrEmpty(t.column_1) && t.column_1.Length >= 3 && t.column_1[2] == '0'
select t;

Of course, you have the entire .NET library at your disposals and could use some sophisticated pattern matching API (like regular expressions) if you need a more general solution:

var regex = new Regex("..0.*");
var qry = from t in table_1
          where regex.Match(t.column_1).Success
          select t;
Isak Savo
Regular expression won't work for L2SQL, which I believe the OP is using (although it's not 100% clear)
Kent Boogaart
oh, didn't know that. But regular string matching techniques works, right?
Isak Savo
+3  A: 

You can use the SqlMethods class. It's part of System.Data.Linq (a.k.a. LINQ to SQL).

from item in db.Table1
where SqlMethods.Like(item.Column1, "__0%")
select item;
Steven