Linq-在字符串列表中查询查询结果

本文关键字:查询 结果 列表 字符串 Linq- | 更新日期: 2023-09-27 18:10:06

我有一个字符串列表

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))

Linq-在字符串列表中查询查询结果

您可能应该将名字推入数据库查询,如下所示:

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;

首先,访问此链接,下载该类并将其添加到App_Code文件夹中:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

然后一定要添加"使用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");

祝你好运!