Monday, 27 February 2012

How to use LIKE, IN - in LINQ

How do we use LIKE (from SQL) in LINQ?

One option:
-> use string.Contains() method

string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook" };
//get companies which have 'oo' in them
IEnumerable<string> companiesWithAnO = (from c in companies
                 where c.Contains("oo")
                 select c).ToArray();


Also we can use string.StartsWith() and EndsWith().

-> Second option: This is only if we are using LINQ To SQL.

string[] companies = { "microsoft", "IBM", "oracle", "google", "apple", "facebook" };
//get companies which have 'oo' in them
IEnumerable<string> companiesWithAnO = from c in companies
             where SqlMethods.Like(c,"%oo%")
             select c;

The IN operator is also quite easy.

string orangeFruit = "orange";
string[] fruitBasket = {"apple","orange","mango","leechy" };
//check orange is in the fruit basket
bool orangeFound = fruitBasket.Contains(orangeFruit);

“Contains” is the extension method in the IEnumerable<T> class.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.