0

次のような文字列があります。

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() がデフォルト値を返し、「#225#」ではなく「02250」が返されることです。# 記号は数値に対応していないため、辞書のエントリはありませんが、.FirstOrDefault() のデフォルトの戻り値を変更またはオーバーライドして、発生したときに # 記号を返すだけにする方法はありますか?私の入力文字列で?

4

2 に答える 2

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();
于 2013-03-07T05:08:05.950 に答える
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 += "#";

    }
于 2013-03-07T05:18:11.940 に答える