我有一个字符串列表
List<string> firstNames = new List<string>();
我有一个查询结果
var contacts = (from p in datacontext.Contact)
如何根据字符串列表查询原始结果(联系人)?
select * from contacts where contacts.firstname like firstNames
类似
firstNames.Any(x=>x.contacts.Contains(x))
答案 0 :(得分:3)
您应该将名字推送到数据库查询中,如下所示:
var contacts = dataContext.Contacts.Where(c => firstNames.Contains(c.FirstName));
现在你在样本查询中使用了“like”,所以也许你想要:
var contacts = dataContext.Contacts
.Where(c => firstNames.Any(f => c.FirstName.Contains(f)));
如果你能提供一些具体的例子,那将有所帮助。
编辑:如果您真的将数据库中的所有联系人拉回(例如)List<Contact> contacts
,那么您可以使用:
var matchingContacts = from contact in contacts
join name in firstNames
on contact.FirstName equals name
select contact;
答案 1 :(得分:0)
首先,访问此链接,下载该类并将其添加到App_Code文件夹:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
然后一定要添加“using System.Linq.Dynamic;”
然后构建您的查询:
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");
祝你好运!