views:

108

answers:

4

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

Use a Regex and call the IsMatch method. The % wildcard maps to .* and the _ wildcard maps to ..

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

Seconded. Contains, StartsWith and EndsWith are the equivalents. There is no "LIKE 'a%b'", but this IS a rare case.

TomTom
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