Linq Contains and StartsWith in Entity Framework 4.1

.net c# entity-framework linq linq-to-entities

Question

Entity Framework Code First is what I'm utilizing. I want to search database entities against List objects. With contains, this works well, but how can I combine it with StartsWith?

Here's my code:

List<string> values = new List<string>();
values.Add("A");
values.Add("B");
context.Customer.Where(c => values.Contains(c.Name)).ToList();

How can I run a query on every client whose name begins with A or B?

1
9
1/12/2012 4:12:02 PM

Accepted Answer

This ought to function in memory, but I'm not sure whether EF could convert it to SQL:

context.Customer.Where(c => values.Any(s => c.Name.StartsWith(s))).ToList();
11
2/5/2012 1:50:09 PM

Popular Answer

Since it plainly includes A or B if it begins with A or B, you don't need to combine it with StartsWith. It must contain A or B in order for it to begin with A or B.

Therefore, just substitute StartsWith for Contains.

context.Customer.Where(c => c.StartsWith("A") || c.StartsWith("B")).ToList(); 


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow