Цикл по массиву - получать все остальные элементы? - PullRequest
1 голос
/ 05 ноября 2011

У меня есть .ini файл INI:

;app ...

    [MSGS]

    title#0 = first title.. 
    message#0 = first message 

    title#1 = second title
    message#1 = second message 

    title#2 = third title
    message#2 = third message  

Я использую Nini lib для разбора. Мне нужно прочитать это в словаре.

Я пробовал это:

 public Dictionary<string, string> Read()
        {
            try
            {
                Dictionary<string, string> result = new Dictionary<string, string>();
                IConfigSource src = config;
                IConfig values = src.Configs["MSGS"];
                string[] keys = values.GetKeys();

                for (int count = keys.Length / 2,i = 0, j = 1; 
                        i < count; i++, 
                        j = i + 1)
                {
                    string titleKey = keys[i];
                    string messageKey = keys[j];
                    string titleVal = values.Get(titleKey);
                    string messageVal = values.Get(messageKey);
                    result.Add(titleVal, messageVal);

                }
            }
            catch (Exception)
            {

            }
            return null;
        }

Вывод:

first title.. : first message
first message : second title
second title : second message

Я хочу:

first title.. : first message
second title : second message
third title : third message

Как мне это сделать? Заранее спасибо. :)

Ответы [ 2 ]

6 голосов
/ 05 ноября 2011
            for (int i = 0; i < keys.Length; i += 2)
            {
                string titleKey = keys[i];
                string messageKey = keys[i+1];
                string titleVal = values.Get(titleKey);
                string messageVal = values.Get(messageKey);
                result.Add(titleVal, messageVal);
            }
2 голосов
/ 05 ноября 2011

В вашем цикле слишком много переменных - j и count не нужны и служат только для запутывания:

for (i = 0; i < keys.Length; i += 2)
{
  string titleKey = keys[i];
  string messageKey = keys[i + 1];
  string titleVal = values.Get(titleKey);
  string messageVal = values.Get(messageKey);
  result.Add(titleVal, messageVal);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...