I am using Linq to Object, now how can i use some thing like "LIKE" used in sql query to filter data?
+3
A:
Use a combination of Contains
, StartsWith
, and EndsWith
. These are all methods or extension methods on System.String
and will work with LINQ. If this doesn't solve your problem, you will be forced to use regular expressions.
David Pfeffer
2010-03-08 14:46:43
A:
Use a Regex and call the IsMatch method. The % wildcard maps to .* and the _ wildcard maps to ..
Robert Davis
2010-03-08 14:49:05
No, never. BAD thing... the moment the same query should run against a database and you do a full table load to the client. Ouch.
TomTom
2010-03-08 14:53:22
The question was about LINQ to Objects, not LINQ to SQL or other database. Some database LINQ providers don't support the Contains, StartsWith, or EndsWith methods, either.
Judah Himango
2010-03-08 14:54:44
A:
Seconded. Contains, StartsWith and EndsWith are the equivalents. There is no "LIKE 'a%b'", but this IS a rare case.
TomTom
2010-03-08 14:54:04
A:
Try this
string searchString = "NAME";
List<string> lstNames = new List<string>()
{"Name1"
,"Name2"
,"Name3"
,"Other names"
,"Something else"};
The below query(s) will accomplish the work
var query1 = (from name in lstNames
where name.ToUpper().Contains(searchString)
select name);
var query2 = lstNames.FindAll(name => name.ToUpper().Contains(searchString));
var query3 = lstNames.Where(name => name.ToUpper().Contains(searchString));
Hope this helps
priyanka.sarkar_2
2010-06-23 04:13:54