循环数组 - 获取其他所有项目?

时间:2011-11-05 18:11:19

标签: c# .net nini

我有一个.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 个答案:

答案 0 :(得分:6)

            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);
            }

答案 1 :(得分:2)

你的循环中有太多变量 - jcount不是必需的,只会让人感到困惑:

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);
}