Linq Contains and StartsWith in Entity Framework 4.1

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

Question

I am using Entity Framework Code First. I want to query entites from database against List objects. This works fine with contains, but how can I combine it with StartsWith?

This is 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 query against all customers which starts with A or B?

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

Accepted Answer

This should work in memory, but I am not sure if it could be translated into SQL by EF:

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

Popular Answer

You don't need to combine it with StartsWith, since if it starts with A or B, then it obviously contains A or B. It can't start with A or B and not contain A or B.

So just use StartsWith instead of 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