Using the Dictionary method in C# [closed]
I am currently using the Dictionary method in C# to index a text file successfully, although in this case I would like to index more than one keyword (#HostName). I have tried adding an additional IF statement to the method although it doesn't appear to work - by that I mean it seems to break the whole method.
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.");
}
}
}
Is it possible to index another term in this method? How could it be done?
Below is the file it is reading:
#CheckName1
HTTP Check
#PortNo1
80
#CheckName2
HTTPS Check
#PortNo2
443
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.");
}
}
}
or use for loop
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.");
}
}
}
Do you mean another test using else if
besides if (ee.Current.StartsWith("#PortNo"))
? I don't see why not. Post (some more) code.
You could use Linq and its ToDictionary()
method instead - this would create a dictionary using any line that start with #
as key, and the next line as value:
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);
There's some overhead involved since this will iterate over the file twice (because is using Zip()
) but that shouldn't matter for a rather small configuration file.
You can use the dictionary then like this:
string someValue = dictionary["#CheckName2"]; //returns "HTTPS Check"
精彩评论