how to use "LIKE" in Linq to Object

4.8k Views Asked by At

I am using Linq to Object, now how can i use some thing like "LIKE" used in sql query to filter data?

4

There are 4 best solutions below

0
David Pfeffer On

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.

2
Robert Davis On

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

0
TomTom On

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

0
AudioBubble On

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