2013-09-24 156 views
0

我想在.net MVC4 C#中创建列表过滤器。 我有ajax查询发送字符串到控制器,并根据数据库中的匹配,它返回记录数。c#字符串比较

所以当StringIsNullOrEmpty()IsNullOrWhiteSpace()它带给我良好的效果。 我现在在匹配值时遇到问题。

虽然它似乎我容易,所以我tried-

控制器

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

但是在这两种情况下它都不起作用。

如何在字符串不匹配时进入第二种方法?

+1

'!String。比较(AccountHead)'不会编译 – Jonesopolis

+1

另外,“在情况A和情况B这么做”的情况下,真的意味着“如果A或(如果)B”并且在C#中被写为“if(A‖B){DoThis ); } –

+1

'String.IsNullOrEmpty(x)&& String.IsNullOrWhiteSpace(x)'与'String.IsNullOrWhiteSpace(x)'相同。为了简洁起见,我会推荐后者。 –

回答

0

您可以使用String.CompareString.Equals相同,但是,它不太简洁,

String.Compare(AccountHead, ledge.AccountHead, StringComparison.OrdinalIgnoreCase) <> 0 

这里的短路...

!AccountHead.Equals(ledge.AccountHead, StringComparison.OrdinalIgnoreCase); 
+0

downvote的理由:S? – James

+0

我看不出任何理由。 +1从我:) – mattytommo

+2

string.Compare返回'int',有'!'不会编译 – Habib

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

您可以使用string.Equals()并为它传递一个用于比较逻辑的选项。事情是这样的:

AccountHead.Equals(ledge.AccountHead, StringComparison.InvariantCultureIgnoreCase) 

这将在不区分大小写的方式使用不变的文化规则比较AccountHeadledge.AccountHead。还有additional options可供选择。

0

你可以保持简单并写下类似的东西!(accountHead == ledge.AccountHead)。 你不需要比较,因为我看到,但要检查字符串是否相等。通常Equals是做这件事的最好方式,但是“==”做语义和object.ReferenceEquals - 参考比较。所以我会去那个。 希望这会有所帮助