2013-03-14 87 views
3

我想一個字符串的最後一個字符比較已知值的列表,如果任何已知值的匹配結束字符,設置一個標誌。我已經想出瞭如何做到這一點與一個字符,但我似乎無法弄清楚如何做到這一點與列表。誰能幫忙?這是我到目前爲止的代碼:比較結束字符列出

StringBuilder myGrade = new StringBuilder(); 

// then I pull some data, calculate some stuff, give a grade, build the string, etc. The resulting text can vary, but the grade letter will always be last. 

var goodGrades = new List<string> { "A", "B", "C" }; 
string endStr = myGrade.ToString(); 
endStr = endStr.Substring(Math.Max(0, endStr.Length - 1)); 
if (endStr == "A") 
    //do some stuff for passing grades 
else 
    //do some other stuff for failing grades 

同樣,這完全適用於單個字符...但我將如何去在goodGrades列表檢查每一個項目?有沒有正則表達式的可能性?先謝謝您的幫助。

+0

你是什麼意思它適用於單個字符?你能向我們展示一個用於多個字符的用例嗎? – James 2013-03-14 16:54:40

回答

5
if(goodGrades.Contains(endStr)) 
{ 
    //Do something. 
} 

此外,這也適用於字符。如果你試圖比較一個角色,這是一個更好的方法。

//Create a list of chars instead of strings 
List<char> goodGrades = new List<char>(){'A', 'B', 'C'}; 
//Get the last char of your string by index 
char endChar = myGrade.ToString()[myGrade.Length - 1]; 

//See if char is contained in list of chars 
if(goodGrades.Contains(endChar)) 
{ 
    //Do something 
} 
+0

謝謝。我仍然在學習,所以我知道它一定很簡單。 Muchas Gracias! – Jeagr 2013-03-14 16:57:04

+1

看看我的編輯。這是爲這種情況做更好的方法。 – Corylulu 2013-03-14 16:57:24

1

msdn

if (goodGrades.Contains(endStr)) 
    do something 
else 
+0

'endStr'應該是最後一個字符。否則它將不起作用 – Anirudha 2013-03-14 17:00:59

+0

謝謝你的幫助。 – Jeagr 2013-03-14 17:05:18

2

只需使用List.Contains

if (goodGrades.Contains(endStr)) { 
    ... 
} 
+0

謝謝。我仍然在學習,所以我知道它一定很簡單。 Muchas Gracias! – Jeagr 2013-03-14 16:57:20

+0

'endStr'應該結束char..right! – Anirudha 2013-03-14 16:58:47

+0

@The_Land_Of_Devils_SriLanka OP代碼中沒有'endChar' – JaredPar 2013-03-14 17:02:04