15

Can any body tell me how can I use a LIKE operator using System.Linq.Dynamic?

I need to add more than one LIKE expression in my dynamic where query

/*
var query =
db.Customers.
Where("CityName Like @0 or CityName Like @1", "London", "USA")
*/
var query =
db.Customers.
Where("CityName Like @0 or CityName Like @1%", "London", "USA")

thanks heaps

chakeda
  • 1,252
  • 1
  • 18
  • 32
Kiarash
  • 1,351
  • 2
  • 12
  • 20

5 Answers5

29

Try using simply "CityName.Contains(@1)" this will convert to the proper lambda since its a method invocation on an accessible type.

something like:

var query =
db.Customers.
Where("CityName.Contains(@0) or CityName.Contains(@1)", "London", "USA")

Just tested it with the sample app that comes with the dynamic library and it generates the LIKE operator

Jaime
  • 6,606
  • 1
  • 23
  • 41
5

You can use .StartsWith(), .EndsWith() and .Contains() which will generate LIKE SQL with trailing, leading and surrounding wildcards respectively. Don't know of a way to generate a statement with an embedded wildcard tho.

Arne Claassen
  • 13,120
  • 3
  • 58
  • 98
4

This will allow the LIKE operator on integer fields:

.Where(searchField + ".ToString().Contains(@0)", searchString);
chakeda
  • 1,252
  • 1
  • 18
  • 32
Dino
  • 41
  • 1
3

Just add more where clauses

var query = db.Customers.Where(c=>c.CityName.contains("London"));
query = query.Where(c=>c.CityName.contains("USA"));
query = query.Where(c=>c.CityName.contains("Johannesburg"));

but the above query will create it :

select * from Customer where CityName like "london" and CityName like "USA" etc...

you want

select * from Customer where CityName like "london" or CityName like "USA" etc...

To use Dynamic Created or statements you can use predicatebuilder there's really alot of functionality there that you can use...

http://www.albahari.com/nutshell/predicatebuilder.aspx

var predicate = PredicateBuilder.False<Customer>();
predicate = predicate.Or(c=>c.CityName.Contains("London"));
predicate = predicate.Or(c=>c.CityName.Contains("USA"));
predicate = predicate.Or(c=>c.CityName.Contains("Johannesburg"));
Gaven
  • 371
  • 1
  • 6
  • I need to use dynamic expression so I should pass criterias as string – Kiarash Jan 05 '11 at 01:16
  • thanks Gavan and sorry for misunderstanding ,I just need to add field dynamicly to the where clause just as string look: Where("CityName Like @0 or CityName Like @1", "London", "USA") has fields in a string and can being generated dynamically but its not a case in your example . but thanks for your company – Kiarash Jan 05 '11 at 05:00
0

you can try this.

IList<string> keyword = new List<string>() { "London", "USA", "Johannesburg" };
            var query = db.Customers.Where(c => keyword.Contains(c.CityName));
  • I like your trick but its not the correct answer cos I need to dynamicly select my field names from string So thanks mate. – Kiarash Jan 06 '11 at 00:16