Like in Lambda Expression and LINQ - c#

How can I do something like this:
customers.where(c=>c.Name **like** "john");
I know this isn't possible but I was wondering how can I have something similar.

customers.Where(c => c.Name.Contains("john"));

If you are targeting LINQ to SQL, use SqlMethods.Like:
customers.Where(c => SqlMethods.Like(c.Name, "%john%"));
Explanation:
The compiler will generate an expression tree from the statement above. Since LIKE is a SQL specific construct and not common to all LINQ Query providers, the SqlMethods class and its members are used as a "hint" for the expression compiler (compiles expression trees to SQL) to emit a LIKE statement.

The first thought that comes to mind is Regex.IsMatch.
This would come closest to providing the kind of functionality you get from LIKE; for instance with it you could do this:
var matches = people.Where(p => Regex.IsMatch(p.Name, "A.*[mn]"));
foreach (Person match in matches)
{
Console.WriteLine(match.Name);
}
And get output like this:
Adam
Aaron
Aidan
Going with string.Contains as others have suggested is almost certainly preferable if your intention is simply to look for a specific substring within Name.

using System.Data.Linq.SqlClient;
...
customers.where(c=>SqlMethods.Like(c.Name, "john"));

Use Regex.IsMatch in your where statement or for a more simpler version without wildcards etc.:
customers.where(c=>c.Name.Contains("john"));

Here is my code :
string s="somethings";
customers.Where(c => c.Name != null && c.Name.ToLower().Contains(s.ToLower()));
Somethings like that.

Related

How to write a statement that generates a LIKE T-SQL statement in System.Linq.Dynamic

I am making use of System.Linq.Dynamic and for most of the time it works out great. However I'm trying to get a StartsWith which would generate something like Description LIKE 'test%' in T-SQL.
What I don't seem to find, and documentation is scarce as I noticed, is which statement to write in my code to pass to the Where method of the Dynamic library to generate that LIKE statement.
Things I already tried but didn't work out for me:
.Where("Description LIKE \"test%\"");
.Where("Description < \"test%\"");
But nothing generates the LIKE statement I'm after.
System.Linq.Dynamic translates your text to regular LINQ expressions, and there is no concept of "LIKE" there. How would you write your like in regular LINQ? Something like that:
ctx.Entity.Where(c => c.Description.StartsWith("test"));
This maps almost exactly to what you should do with dynamic linq:
// #0 is first parameter, which is "test" in this case
ctx.Entity.Where("Description.StartsWith(#0)", "test");
You can pass value inline too, though I'd recommend to always use parameters like above
ctx.Entity.Where("Description.StartsWith(\"test\")");
You can replace StartsWith with Contains or EndsWith to generate their respective tsql "LIKE" equivalents.
I haven't used this library, but they have an example that generates a LIKE statement. Does that fit your use?
For posterity, here's the code:
var q = from c in db.Customers
where SqlMethods.Like(c.CustomerID, "C%")
select c;

Like condition in MVC4 using lambda

Is there a way for me to do like condition just like query in MVC using lambda? I currently have:
return repository.GetAll().Where(
m => string.(m.Name, name, StringComparison.OrdinalIgnoreCase));
So how do I make this into a like condition?
use Contains() or StartsWith() or EndsWith() according to your requirement:
var filtered= data.Where(x=> x.Name.ToLower().Contains(name.ToLower()));
in your code:
return repository.GetAll().Where(
m => m.Name.ToLower().Contains(name.ToLower()));
Usually you would use m.Name.Contains, that isn't possible here since it doesn't support case in-sensitiveness, like you have written down now. (if that is not intentional, use m.Name.Contains(name))
Another option mentioned here is the use of CompareInfo.IndexOf, but I don't know if it works well with EF.
Give this a try:
repository
.GetAll()
.Where
( m => CultureInfo.InvariantCulture.CompareInfo
.IndexOf(m.Name, name, CompareOptions.IgnoreCase) > 0
)
The only way I have managed this before is with raw sql syntax e.g.
context.Blogs.SqlQuery("SELECT * FROM SomeTable WHERE SomeTable.Name like {0}", name);

LINQ: Multiple LIKE clauses in a single predicate

I'd like to do a LINQ query that can compare multiple variables to a single string. I've seen LINQ for LIKE queries of array elements, and it's helpful, but not quite. I need the reverse.
What I'd like to do is the following: let's say I have a Company object with both Name and Address. I also have a string keyword. Then, I'd like to find all Companys in a list that have the keyword in either their Name or Address. In SQL it would be...
SELECT * FROM Company
WHERE Name LIKE '%keyword%' OR Address LIKE '%keyword%'
I've been using Entity Framework, and I've tried the following: context.Companies.Where(x => new string[] { x.Name, x.Address }.Contains(keyword), as well as context.Companies.Where(x => new string[] { x.Name, x.Address }.Any(r => r.Contains(keyword)), but neither were successful. The first one gives me an IN clause, and the second one... I don't know what it does, but it doesn't give me what I want.
I'm sorry I don't have a very in-depth understanding of Expressions (yet); I wished I was able to write my own custom Expressions from scratch, but scratch it I can't just yet... Can anybody help me with this?
Any reason for not just using the || operator?
context.Companies.Where(x => x.Name.Contains(keyword) ||
x.Address.Contains(keyword))
I'd expect this to be translated into your original SQL.

Entity Framework: How to express a LIKE statement that contains [0-9]

I would like to construct a LINQ query for use against an EF context that selected rows based on a LIKE condition.
As I understand you can get this behaviour using .Contains(). However, the LIKE I would like to include contains a number range:
LIKE 'LN[0-9]%'
for example...
How would I go about replicating this behaviour in a simple query?
Thanks,
Currently u can't use like in LINQ directly. U can use StartsWith, Contains or EndsWith that are translated to LIKE. Other solution is using 'Where' overide with 'string' like this:
Where("something LIKE 'LN[0-9]%'")
Here is example
try StartsWith like so:
var query = Cities.Where(city => city.Code.StartsWith("LN[0-9]"));
This is a regex problem ([0-9] is a regex nomenclature). I suggest you try something like this:
Regex myRegex = new Regex("LN[0-9]");
var matches = Cities.Where(c => myRegex.IsMatch(c.Field));
A crude example but should get you started.

Dynamically evaluating string conditions in C#

I have a collection of strings. I need to find out from this collection strings which satisfies some condition e.g. that string contains A and B or C. These criteria are specified by the user so they are dynamic. In Linq it should be something like,
List<String> items = new List<string> { "sdsdsd", "sdsd", "abc"};
var query = from item in items
where item.Contains("a") && item.Contains("b") || item.Contains("c")
select item;
I want to make the where condition dynamic so that it can work for any input by the user. Is it possible to do this in C# without using any external library. Maybe using Linq or something else which is builtin into .Net framework.
Thanks,
Gary
Although you don't want to use external libraries, there is one which is just fantastic, and that is PredicateBuilder. Predicate builder allows you to build up a set of predicates to match items against, e.g.:
var predicate = PredicateBuilder.True<string>();
predicate = predicate
.And(p => p.Contains("a"))
.And(p => p.Contains("b"));
var matches = items.Where(predicate);
If you want to do it on your own, start here:
Dynamic Predicates:
http://msdn.microsoft.com/en-us/library/bb513731.aspx
Dynamic Expression Trees:
http://msdn.microsoft.com/en-us/library/bb882637.aspx
I think this is more than you wanted, and would strongy suggest to use some (lightweight) ready and tested library, that does the conversion from user-strings to runtime-queries for you.
(source: scottgu.com)
You need something like this? Use the Linq Dynamic Query Library (download includes examples).
Check out ScottGu's blog for more examples.

Categories