L
L
LiptonOlolo2016-07-15 17:59:42
C++ / C#
LiptonOlolo, 2016-07-15 17:59:42

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

And there is a filling of this very library:
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]);
    }
  }
});

And there is "reading" by key IniFormat:
public string Read(string Case, string Key)
{
  IniFormat ini = new IniFormat()
  {
    Case = Case,
    Key = Key
  };
  
  return values.ContainsKey(ini) ? values[ini] : "";
}

The essence of the problem is that he does not want to see in any way that there is a key in the library.
What's the trouble?
Thank you.

Answer the question

In order to leave comments, you need to log in

4 answer(s)

Беда в том, что нужно читать теорию. примеры
Не задан comparer и не переопределен equals(t) и equals (gethashcode)
Словарь сортирует по умолчанию,по умолчанию все ini объекты разные, если являются разными ссылками

Сергей Кузьмин, 2016-07-15
@Flashmond

Дело в том, что ключом у вас является уникальный объект. И ищется соответственно не по значению, а по ссылке. А два разных объекта не ссылаются на один участок памяти, соответственно считается, что у вас такого ключа нет. Как решение могу предложить:
а) Вложенный словарь Dictionary<string, Dictionary<string, string> >
б) Для поиска просматривать все элементы и сравнивать значение в ключе.

foreach ( IniFormat key in values.Keys )
{
if ( key.Case == Case && key.Key == Key )
  return values[key];
}

G
GavriKos, 2016-07-15
@GavriKos

Скорее всего потому, что в данном случае ключом является уникальный инстанс IniFormat. Сравнение по значению Case и Key не проводится.

L
LiptonOlolo, 2016-07-15
@LiptonOlolo Автор вопроса

Все, понял, я тупой, IniFormat надо было сделать структурой.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question