Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1 Linq Contains and StartsWith

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?

like image 427
LuckyStrike Avatar asked Jan 12 '12 16:01

LuckyStrike


2 Answers

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();
like image 153
Sergey Kalinichenko Avatar answered Nov 13 '22 14:11

Sergey Kalinichenko


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(); 
like image 1
Erik Funkenbusch Avatar answered Nov 13 '22 12:11

Erik Funkenbusch