使用c#中的Dictionary方法

本文关键字:方法 Dictionary 中的 使用 | 更新日期: 2023-09-27 18:09:52

我目前正在使用c#中的Dictionary方法来成功索引文本文件,尽管在这种情况下我想索引多个关键字(#HostName)。我试过在方法中添加一个额外的IF语句,尽管它似乎不起作用——我的意思是它似乎破坏了整个方法。

 var dictionary = new Dictionary<string, string>();
 var lines = File.ReadLines("probe_settings.ini");
 var ee = lines.GetEnumerator();
 while (ee.MoveNext())
 {
     if (ee.Current.StartsWith("#PortNo"))
     {
         string test = ee.Current;
         if (ee.MoveNext())
         {
             dictionary.Add(test, ee.Current);
         }
         else
         {
             throw new Exception("File not in expected format.");
         }
     }
 }

是否可以在此方法中索引另一项?怎么能做到呢?

下面是正在读取的文件:

#CheckName1
HTTP Check
#PortNo1
80
#CheckName2
HTTPS Check
#PortNo2
443

使用c#中的Dictionary方法

 while (ee.MoveNext())
 {
     if (ee.Current.StartsWith("#MatchOne") || ee.Current.StartsWith("#MatchTwo"))
     {
         string test = ee.Current;
         if (ee.MoveNext() && !dictionary.ContainsKey(test))
         {
             dictionary.Add(test, ee.Current);
         }
         else
         {
             throw new Exception("File not in expected format.");
         }
     }
 }

或使用for循环

for( int i =0 ; i < lines.length -1 ;i++)
{
         if (!string.IsNullOrEmpty(lines[i]) && lines[i].StartsWith("#MatchOne") || lines[i].StartsWith("#MatchTwo"))
         {
             string test = lines[i];
             if ( !dictionary.ContainsKey(test))
             {
                 dictionary.Add(test, lines[i+1]);
             }
             else
             {
                 throw new Exception("File not in expected format.");
             }
         }
}

您的意思是除了if (ee.Current.StartsWith("#PortNo"))外,还使用else if进行测试吗?我看没什么不可以的。Post(更多)代码

您可以使用Linq和它的ToDictionary()方法来代替-这将创建一个字典,使用以#开头的任何行作为键,下一行作为值:

var lines = File.ReadAllLines("probe_settings.ini");
var dictionary = lines.Zip(lines.Skip(1), (a, b) => new { Key = a, Value = b })
                      .Where(l => l.Key.StartsWith("#"))
                      .ToDictionary(l => l.Key, l => l.Value);

这涉及到一些开销,因为这将在文件上迭代两次(因为使用Zip()),但对于一个相当小的配置文件来说,这应该无关紧要。

你可以这样使用字典:

string someValue = dictionary["#CheckName2"]; //returns "HTTPS Check"