Good afternoon. I have a strange problem. When iterating through the list, SortedDictionary does not recognize the key. Namely, it gives out that the key was not found. System.Collections.Generic.KeyNotFoundException
Moreover, an error is issued only when more than 2 elements are added to the list. At the same time, if 3 elements are wrong on the 1st, if 5 then on the 1st and 3rd, 4 again on the 1st.
public: Collections::Generic::SortedDictionary<Product_for_sale^, int> products;
void Score:: setProductsLabel() {
int y = 50;
productLabels.Clear();
for each (Product_for_sale ^ key in products.Keys) {
String^ product_by_score = "";
System::Windows::Forms::Label^ info = (gcnew System::Windows::Forms::Label());
if (products[key] > 0) {
product_by_score = key->getName() + " | " + products[key] +
" | " + key->getFullPrice() * products[key] + "\n";
info->BackColor = System::Drawing::Color::Red;
}
else {
info->BackColor = System::Drawing::Color::PaleGreen;
product_by_score = key->getName() + " | " + "СОБРАНО" +
" | " + key->getFullPrice() * products[key] + "\n";
}
info->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10.00F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
info->AutoSize = true;
info->Location = System::Drawing::Point(10, y);
info->Name = L"label4";
info->Size = System::Drawing::Size(100, 25);
info->TabIndex = 2;
info->Text = product_by_score;
productLabels.Add(key,info );
y += 30;
}
}
//реализация сравнения в классе Product_for_sale
int Product_for_sale::equals(Product_for_sale^ pfs) {
if (this->name->Equals(pfs->getName())) {
return 0;
}
else return 1;
}
int Product_for_sale::CompareTo(Object^ obj){
if (obj->GetType() == Product_for_sale::typeid) {
Product_for_sale^ product = dynamic_cast<Product_for_sale^>(obj);
return equals(product);
}
else return 1;
// throw gcnew ArgumentException("object is not a Score");
}
The error crashes precisely on the expression products[key] with the key itself, you can work and get data from the object.
I checked the occupancy of the list at the entrance, everything is correct, both the key and the value. And again, if there are 2 pairs in the list, everything works without problems.
In the provided equals method, it returns 0 if the names are equal and 1 if they are not. This doesn't follow the standard convention. Replace the whole snippet as below: