Reputation: 21
I have a list of strings
List<string> firstNames = new List<string>();
I have a query result
var contacts = (from p in datacontext.Contact)
How Can I Query the original result (contacts) against the list of strings?
select * from contacts where contacts.firstname like firstNames
something like
firstNames.Any(x=>x.contacts.Contains(x))
Upvotes: 2
Views: 1859
Reputation: 5223
First, visit this link, download the class and add it to your App_Code folder: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Then be sure to add "using System.Linq.Dynamic;"
Then construct your query like this:
DatabaseDataContext db = new DatabaseDataContext();
List<string> firstNames = new List<string>();
//--- loop through names and build a where query
string WhereClause = string.Empty;
for (int i = 0; i < firstNames.Count(); i++)
{
string s = firstNames[i].ToLower();
if (i != Communities.Length - 1)
WhereClause += "FirstName.ToLower().Contains(\"" + s + "\") OR "; //--- first name is the field name in the db
else
WhereClause += "FirstName.ToLower().Contains(\"" + s + "\")";
}
//--- execute query and pass the dynamic where clause
IQueryable contacts = db.Contacts
.Where(WhereClause)
.OrderBy("FirstName");
Good Luck!
Upvotes: 0
Reputation: 1503869
You should probably push the first names into the database query, like this:
var contacts = dataContext.Contacts.Where(c => firstNames.Contains(c.FirstName));
Now you used "like" in your sample query, so maybe you want:
var contacts = dataContext.Contacts
.Where(c => firstNames.Any(f => c.FirstName.Contains(f)));
If you could provide some concrete examples it would help.
EDIT: If you're really pulling back all the contacts from the database already into (say) a List<Contact> contacts
, then you could use:
var matchingContacts = from contact in contacts
join name in firstNames
on contact.FirstName equals name
select contact;
Upvotes: 3