【问题标题】:Convert SQL query to Linq for not in将 SQL 查询转换为 Linq for not in
【发布时间】:2018-04-01 09:54:18
【问题描述】:

如何将此 SQL 查询转换为 Linq? 有一个我无法转换的 not in 语句。

SQL

Select keyword from SW_TBL_KEYWORD 
where keyword_scope='A' and 
keyword not in ('ATRF', 'CAST','EVAL', 'FTBS', 'KYCB', 'RCAN', 'RDPT','REGA', 'REGC' )

灵巧

    public static IEnumerable<SelectListItem> GetProductName()
    {
        using (WALLET_CORE_UATEntities _ent = new WALLET_CORE_UATEntities())
        {
            return new SelectList(_ent.SW_TBL_KEYWORD.Where(x => x.Keyword_Scope == "A" && x.Keyword!= "ATRF" 
            && x.Keyword!= "CAST" 
            && x.Keyword != "EVAL"
            && x.Keyword != "FTBS"
            && x.Keyword != "KYCB"
            && x.Keyword != "RCAN"
            && x.Keyword != "RDPT"
            && x.Keyword != "REGA"
            && x.Keyword != "CAST"
            && x.Keyword != "REGC")
            .ToList(),"Keyword","Keyword_Description");
        }

    }

【问题讨论】:

标签: .net model-view-controller


【解决方案1】:

你可以使用Contains方法的否定:

private static readonly HashSet<string> excludeKeywords = 
    new HashSet<string>(StringComparer.CurrentCultureIgnoreCase)
    { "ATRF", "CAST", "EVAL", "FTBS", "KYCB", "RCAN", "RDPT", "REGA", "CAST", "REGC" };

public static IEnumerable<SelectListItem> GetProductName()
{
    using (WALLET_CORE_UATEntities _ent = new WALLET_CORE_UATEntities())
    {
        var result = _ent.SW_TBL_KEYWORD.Where(x =>
            x.Keyword_Scope == "A" &&
            !excludeKeywords.Contains(x.Keyword));  /* NOT IN check */

        return new SelectList(result.ToList(), "Keyword", "Keyword_Description");
    }
}

【讨论】:

  • /*这里*/中要包含的内容
  • 什么都没有;我添加了该注释以表明这是执行 NOT IN 检查等效项的行。我会修改评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多