Answer the question
In order to leave comments, you need to log in
Why doesn't the Dictionary see the key?
Good afternoon.
There is a library:
Dictionary<IniFormat, string> values = new Dictionary<IniFormat, string>();
class IniFormat
{
public string Case { get; set; }
public string Key { get; set; }
}
string[] lines = File.ReadAllLines(IniFilePath);
string CurrentCase = "";
lines.ToList().ForEach(x =>
{
if (x.StartsWith("[") && x.EndsWith("]"))
{
CurrentCase = x.Substring(1, x.Length - 2);
}
else
{
if (!x.StartsWith("#") && x.Length > 1)
{
IniFormat add = new IniFormat()
{
Case = CurrentCase,
Key = x.Split('=')[0]
};
values.Add(add, x.Split('=')[1]);
}
}
});
public string Read(string Case, string Key)
{
IniFormat ini = new IniFormat()
{
Case = Case,
Key = Key
};
return values.ContainsKey(ini) ? values[ini] : "";
}
Answer the question
In order to leave comments, you need to log in
Беда в том, что нужно читать теорию. примеры
Не задан comparer и не переопределен equals(t) и equals (gethashcode)
Словарь сортирует по умолчанию,по умолчанию все ini объекты разные, если являются разными ссылками
Дело в том, что ключом у вас является уникальный объект. И ищется соответственно не по значению, а по ссылке. А два разных объекта не ссылаются на один участок памяти, соответственно считается, что у вас такого ключа нет. Как решение могу предложить:
а) Вложенный словарь Dictionary<string, Dictionary<string, string> >
б) Для поиска просматривать все элементы и сравнивать значение в ключе.
foreach ( IniFormat key in values.Keys )
{
if ( key.Case == Case && key.Key == Key )
return values[key];
}
Скорее всего потому, что в данном случае ключом является уникальный инстанс IniFormat. Сравнение по значению Case и Key не проводится.
Все, понял, я тупой, IniFormat надо было сделать структурой.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question