Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Query using Contains and not contains

I am trying to fetch records from database in the sense that it should getrecords where name contains "searchKey" and name not in the excludeTerms array with comma seperated. How can I do this in 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();

Where excludeTerms contains list of elements, such as

1)Sandy
2)Mandy
3)Larry etc

List<string> excludeTerms = new List<string>();
like image 420
Sweetie Avatar asked Dec 13 '13 13:12

Sweetie


1 Answers

Unfortunately you can use local sequences only with Contains operator (which is translated into SQL IN operator). So, you can move whole filtering to memory

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

Or just filtering out excluded terms:

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();
like image 74
Sergey Berezovskiy Avatar answered Sep 30 '22 04:09

Sergey Berezovskiy