Linq Query使用Contains而不包含

时间:2013-12-13 13:02:20

标签: c# asp.net sql-server asp.net-mvc-3 linq-to-sql

我试图从数据库中获取记录 它应该记录名称包含“searchKey”的名称,并且名称不在逗号分隔的excludeTerms数组中。 我怎么能在Linq中做到这一点?

 Rows = (from u in DB.Clients
         where u.Name.Contains(searchTerm) && !u.Name.Contains(string.Join(",", excludeTerms.Select(s => "'" + s + "'").ToArray()))
         select new ClientModel
         {
            Name = u.FullName,
            Id = u.Id,
         }).Take(5).ToList();

其中excludeterma包含假设的元素列表

1)Sandy
2)Mandy
3)Larry etc

List<string> excludeTerms = new List<string>();

1 个答案:

答案 0 :(得分:10)

不幸的是,您只能将本地序列与Contains运算符(将其转换为SQL IN运算符)一起使用。因此,您可以将整个过滤移动到内存

Rows = (from u in DB.Clients.AsEnumerable()
        where u.Name.Contains(searchTerm) &&
             !excludeTerms.Any(s => u.Name.Contains(s))
         select new ClientModel {
              Name = u.FullName,
              Id = u.Id,
         }).Take(5).ToList();

或者只是过滤掉排除的字词:

Rows = (from u in DB.Clients
        where u.Name.Contains(searchTerm)                 
        select new ClientModel {
              Name = u.FullName,
              Id = u.Id,
        }).AsEnumerable()
          .Where(m => !excludeTerms.Any(s => m.Name.Contains(s)))
          .Take(5).ToList();