如何在 entity framework 中使用 linq 在 where 条件下使用 "not equal to"

how to use "not equal to" in where condition using linq with entity framework

如何在 entity framework 的 LINQ 条件下使用 "not equal to"。

public ActionResult ViewOfficeType()
{            
   return View(entity.TBL_OFFICETYPE.Where(p => p.STATUS<>"D").ToList());
}

it shows invalid expression '>'

如果我使用 '!='。它不显示 error.But 它不起作用。

您可以在 Equals()

上使用 ! 运算符
public ActionResult ViewOfficeType()
{            
    return View(entity.TBL_OFFICETYPE.Where(p => !p.Equals("D")).ToList());
}

您可以使用以下方法

  1. 在 lambda 表达式中使用 != 运算符

public ActionResult ViewOfficeType()
{            
   return View(entity.TBL_OFFICETYPE.Where(p => p.STATUS != "D").ToList());
}

  1. 使用 !string.Equals

public ActionResult ViewOfficeType()
{            
   return View(entity.TBL_OFFICETYPE.Where(p => !p.STATUS.Equals("D")).ToList());
}

注意:注意字符编码和区分大小写等字符串比较问题

我更喜欢如下扩展方法:

public static class StringExtension
{
    public static bool NotEquals(this string source, string target)
    {
        return !(source.Equals(target));        
    }
}

工作原理:

   string source = "Test"; // Sample / Source data

//用"test"测试,结果为真,由于大小写不同,所以两个字符串不同

   source.NotEquals("test"); 

// 使用 "Test" 进行测试,结果为假,因为它们相同

   source.NotEquals("Test"); 

扩展方法里面还有很多可能,根据你是否要忽略大小写,你可以简单地在 Equals 方法中传递 StringComparison.OrdinalIgnoreCase,然后 "Test" 将被计算为等于"test"(忽略大小写)

var status = entity.TBL_OFFICETYPE.Select(p => p.STATUS == "D");
           return View(entity.TBL_OFFICETYPE.Where(p => !status.Contains(p.STATUS == "D")).ToList());

请试试这个