You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含NOT IN子句的SQL查询转换为Linq语句?

Fixing the LINQ NOT IN Logic for Your Query

Got it, let's clean up that LINQ code to properly match your original SQL's NOT IN clause. Instead of chaining a bunch of && x.Keyword != ... checks, we can use a collection and the negation of Contains()—it's cleaner, more maintainable, and directly maps to the SQL logic you want.

Here's the complete, working code:

public static IEnumerable<SelectListItem> GetProductName()
{
    // Create a list of excluded keywords (matches the NOT IN values from your SQL)
    var excludedKeywords = new List<string> 
    { 
        "ATRF", "CAST", "EVAL", "FTBS", "KYCB", 
        "RCAN", "RDPT", "REGA", "REGC" 
    };

    using (WALLET_CORE_UATEntities _ent = new WALLET_CORE_UATEntities())
    {
        return _ent.SW_TBL_KEYWORD
            // Filter by scope AND exclude the specified keywords
            .Where(x => x.Keyword_Scope == "A" && !excludedKeywords.Contains(x.Keyword))
            // Map each matching record to a SelectListItem
            .Select(x => new SelectListItem
            {
                Text = x.Keyword,
                Value = x.Keyword // Use this if you want value and text to be the same; adjust if needed
            })
            // Materialize the query to avoid issues with the disposed context
            .ToList();
    }
}

Key Notes:

  • NOT IN Equivalent: The !excludedKeywords.Contains(x.Keyword) is LINQ's way of writing keyword NOT IN (...)—it tells EF to generate the same NOT IN SQL clause under the hood.
  • Maintainability: Storing excluded keywords in a list makes it easy to add/remove values later without messing with the query logic.
  • Context Disposal: Calling .ToList() ensures the query runs immediately inside the using block. If you skip this, the query would try to execute later when the context is already disposed, causing an error.
  • Explicit Mapping: Using .Select() to create SelectListItem makes your intent clear, instead of relying on SelectList to guess which properties to use.

内容的提问来源于stack exchange,提问作者Aayush Rajopadhyaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:31