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 excludeterma contains list of elements suppose
1)Sandy
2)Mandy
3)Larry etc
List excludeTerms = new List();
解决方案
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();