使用LINQ查询包含不包含 [英] Linq Query using Contains and not contains

查看:3070
本文介绍了使用LINQ查询包含不包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这个意义来从数据库记录该
它应该在哪里名称中包含searchKey和名称不excludeTerms阵列逗号分隔getrecords。
我怎样才能做到这一点的LINQ?

 行数=(从u在DB.Clients
         其中,u.Name.Contains(SEARCHTERM)及&放大器; !u.Name.Contains(的string.join(,,excludeTerms.Select(S =>中S +').ToArray()))
         选择新ClientModel
         {
            名称= u.FullName,
            ID = u.Id,
         })采取(5).ToList();

在这里excludeterma包含的元素列表假设

  1)桑迪
2)曼迪
3)拉里等


 列表<串GT; excludeTerms =新的List<串GT;();


解决方案

不幸的是,你可以使用本地序列只包含运营商(这是转换成SQL IN操作符)。所以,你可以整个过滤移动到内存

 行数=(从u在DB.Clients.AsEnumerable()
        其中,u.Name.Contains(SEARCHTERM)及&放大器;
             !excludeTerms.Any(S => u.Name.Contains(S))
         选择新ClientModel {
              名称= u.FullName,
              ID = u.Id,
         })采取(5).ToList();

或者只是筛选出排除条款:

 行数=(从u在DB.Clients
        其中,u.Name.Contains(SEARCHTERM)
        选择新ClientModel {
              名称= u.FullName,
              ID = u.Id,
        })。AsEnumerable()
          。凡(M =>!excludeTerms.Any(S => m.Name.Contains(S)))
          。取(5).ToList();

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<string> excludeTerms = new List<string>();

解决方案

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

这篇关于使用LINQ查询包含不包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆