2013-09-24 157 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 - 參考比較。所以我會去那個。 希望這會有所幫助