2013-05-19 122 views
3

我認爲我的代碼應該使ViewBag.test屬性等於"No Match",而是它拋出一個InvalidOperationException這段代碼爲什麼會拋出InvalidOperationException異常?

這是爲什麼?

string str = "Hello1,Hello,Hello2"; 
string another = "Hello5"; 
string retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 
        .First(p => p.Equals(another)); 
if (str == another) 
{ 
    ViewBag.test = "Match"; 
} 
else 
{ 
    ViewBag.test = "No Match"; //this does not happen when it should 
} 
+0

@SLaks代碼返回,而不是在頁面上diplay 「不匹配」 System.InvalidOperationException。 – user2398766

+0

它不** **回報'InvalidOperationException',它把它扔了。主要是因爲該列表中沒有等於「Hello5」的字符串。你想完成什麼? –

+2

。首先()拋出它,如果沒有匹配,嘗試FirstOrDefault(),並檢查空 –

回答

10

正如你可以看到here,當它被稱爲序列爲空的First方法拋出InvalidOperationException。由於沒有分割的結果元素等於Hello5,結果是空列表。在該列表上使用First將拋出異常。

請考慮使用FirstOrDefault代替(記錄爲here),而不是在序列爲空時引發異常,而是返回默認值爲可枚舉類型。在這種情況下,調用的結果將是null,你應該在其餘代碼檢查這一點。

使用Linq方法(記錄here)可能會更清潔,該方法返回bool

string str = "Hello1,Hello,Hello2"; 
string another = "Hello5"; 
bool retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 
        .Any(p => p.Equals(another)); 
if (retVal) 
{ 
    ViewBag.test = "Match"; 
} 
else 
{ 
    ViewBag.test = "No Match"; //not work 
} 

而現在使用ternary operator強制性一個班輪:

string str = "Hello1,Hello,Hello2"; 
string another = "Hello5"; 
ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 
        .Any(p => p == another) ? "Match" : "No Match"; 

請注意,我用的也是==這裏比較字符串,這被認爲是C#更地道。

+1

我** **就這給予好評,但代碼的不清楚我已經完全不知道他(她)正試圖做。 –

+1

我理解,使得他或她正試圖設置'ViewBag.test'爲「匹配」的時候,變量'str'包含逗號之間的變量'another',和「不匹配」,否則這個問題。這是你的意思,@ user2398766? –

+0

我同意這一點,但我不知道! –

2

這給一個鏡頭:

bool hasMatch = str.Split(',').Any(x => x.Equals(another)); 

ViewBag.test = hasMatch ? "Match" : "No Match"; 
相關問題