我正在尝试在.net MVC4 C#中创建列表过滤器。 我有一个ajax查询,它将字符串发送到控制器,根据数据库中的匹配,它返回记录数。
所以当String
为IsNullOrEmpty()
和IsNullOrWhiteSpace()
时,它会给我带来很好的结果。
我现在在匹配值时遇到问题。
虽然看起来很容易所以我试过 -
控制器
public ActionResult SearchAccountHead(string accountHead)
{
var students = from s in db.LedgerTables
select s;
List<LedgerModel> ledge = null;
if (!String.IsNullOrEmpty(accountHead))
{
//Returns non-empty records
}
if (String.IsNullOrEmpty(accountHead) && String.IsNullOrWhiteSpace(accountHead))
{
//Checks whether string is null or containing whitespace
//And returns filtered result
}
return PartialView(ledge);
}
现在,如果我的字符串与我在控制器中使用的字符串不匹配,那么我尝试映射它 -
if (String.IsNullOrEmpty(accountHead) && String.IsNullOrWhiteSpace(accountHead) && !String.Compare(accountHead))
if (String.IsNullOrEmpty(accountHead) && String.IsNullOrWhiteSpace(accountHead) && !String.Compare(AccountHead,ledge.AccountHead))
但在这两种情况下它都不起作用。
当字符串不匹配时,如何进入第二种方法?
答案 0 :(得分:2)
您无法将string.Compare
与!
一起使用,因为string.Compare
会返回一个整数值。如果你正在比较字符串的相等性,那么如果你使用string.Equals
它会更好,它也有一个过载,它会进行不区分大小写的比较。
您可以使用以下支票:
if (String.IsNullOrWhiteSpace(accountHead) &&
!String.Equals(AccountHead, ledge.AccountHead,StringComparison.InvariantCultureIgnoreCase))
作为旁注,您可以删除
if (String.IsNullOrEmpty(AccountHead) && String.IsNullOrWhiteSpace(AccountHead))
然后使用
if (String.IsNullOrWhiteSpace(AccountHead))
因为string.IsNullOrWhiteSpace
也检查空字符串。
答案 1 :(得分:1)
您可以使用string.Equals()
并为其传递比较逻辑选项。像这样:
AccountHead.Equals(ledge.AccountHead, StringComparison.InvariantCultureIgnoreCase)
这将使用不变的文化规则以不区分大小写的方式比较AccountHead
和ledge.AccountHead
。还有additional options可供选择。
答案 2 :(得分:0)
您可以使用String.Compare执行与String.Equals
相同的操作,但是,它有点不那么简洁,例如
String.Compare(AccountHead, ledge.AccountHead, StringComparison.OrdinalIgnoreCase) <> 0
这是更短的方式......
!AccountHead.Equals(ledge.AccountHead, StringComparison.OrdinalIgnoreCase);
答案 3 :(得分:0)
你可以保持简单并写下这样的东西!(accountHead == ledge.AccountHead)。 我不需要比较,但要检查字符串是否相等。通常Equals是执行此操作的最佳方式,但“==”执行语义和object.ReferenceEquals - 引用比较。所以我会选择那个。 希望这有帮助