2013-03-07 24 views
0

我有一個這樣的字符串:轉換 「#BAL#」 到 「#225#」 用C#

string ussdCommand = "#BAL#"; 

我想將其轉換成 「#225#」。目前,我已經定義了這樣的解釋:

Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
dictionary.Add("ABC", 2); 
dictionary.Add("DEF", 3); 
dictionary.Add("GHI", 4); 
dictionary.Add("JKL", 5); 
dictionary.Add("MNO", 6); 
dictionary.Add("PQRS", 7); 
dictionary.Add("TUV", 8); 
dictionary.Add("WXYZ", 9); 

然後,我有一個不接受我的原字符串(「#BAL#」),並將其轉換這樣的功能:

private static string ConvertLettersToPhoneNumbers(string letters) 
{ 
    string numbers = string.Empty; 
    foreach (char c in letters) 
    { 
     numbers += dictionary.FirstOrDefault(d => d.Key.Contains(c)).Value.ToString(); 
    } 
    return numbers; 
} 

正如你馬上注意到的那樣,問題是我的字典不包含「#」的條目,因此.FirstOrDefault()返回默認值,我返回的是「02250」而不是「#225#」。我沒有#號字典條目,因爲它不對應一個數字,但有沒有辦法修改或覆蓋.FirstOrDefault()中的默認返回值,以便它在任何時候只發回#號在我的輸入字符串?

回答

2

我會改變它使用Dictionary<char, char>,並使用TryGetValue輕鬆找出是否有一個映射:

private static readonly Dictionary<char, char> PhoneMapping = 
    new Dictionary<char, char> 
{ 
    { 'A', '2' }, { 'B', '2' }, { 'C', '2' }, 
    { 'D', '3' }, { 'E', '3' }, { 'F', '3' }, 
    { 'G', '4' }, { 'H', '4' }, { 'I', '4' }, 
    { 'J', '5' }, { 'K', '5' }, { 'L', '5' }, 
    { 'M', '6' }, { 'N', '6' }, { 'O', '6' }, 
    { 'P', '7' }, { 'Q', '7' }, { 'R', '7' }, { 'S', '7' }, 
    { 'T', '8' }, { 'U', '8' }, { 'V', '8' }, 
    { 'W', '9' }, { 'X', '9' }, { 'Y', '9' }, { 'Z', '9' } 
}; 

private static string ConvertLettersToPhoneNumbers(string letters) 
{ 
    char[] replaced = new char[letters.Length]; 
    for (int i = 0; i < replaced.Length; i++) 
    { 
     char replacement; 
     replaced[i] = PhoneMapping.TryGetValue(letters[i], out replacement) 
      ? replacement : letters[i]; 
    } 
    return new string(replaced); 
} 

注意,對於其他情況下,您希望有一個「第一,但有一個默認的」您可以使用:

var foo = sequence.DefaultIfEmpty(someDefaultValue).First(); 
+0

謝謝喬恩。這是一個好主意! – user685869 2013-03-07 05:12:00

+0

謝謝你的.DefaultIfEmpty()解釋。 – user685869 2013-03-07 05:14:17

0

其工作

protected void Page_Load(object sender, EventArgs e) 
    { 
     Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
     dictionary.Add("ABC", 2); 
     dictionary.Add("DEF", 3); 
     dictionary.Add("GHI", 4); 
     dictionary.Add("JKL", 5); 
     dictionary.Add("MNO", 6); 
     dictionary.Add("PQRS", 7); 
     dictionary.Add("TUV", 8); 
     dictionary.Add("WXYZ", 9); 


     string value = "BAL"; 
     string nummber = "#"; 
     foreach (char c in value) 
     { 

      nummber += dictionary.FirstOrDefault(d => d.Key.Contains(c)).Value.ToString(); 
     } 
     nummber += "#"; 

    }