I was a homework, I had to implement some method. I can do the upload method, where I had to upload an dictionary in elements. If the Key had already in the Dictionary I had to update the Value. If the key wasn’t in the Dictionary, I had to add that element. In Foreach I could do that.
In the method never true in the if case, only the else case execute. ( In other way I tried to if(alcDictionary.Keys==alc) -but isn’t work). I don’t know why. Somebody can explain me where is my problem? Why never execute the If case. (Always write out “dont find”, and not the “find”)
I’ve written this method with containsKey():
public void Upload(Alcohol alc, int dl)
{
int d = 0;
Alcohol s = null;
if (alcDictionary.ContainsKey(alc))
{
Console.WriteLine("I find");
d = alcDictionary[alc];
alcDictionary[alc] = d + dl;
}
else
{
Console.WriteLine("dont find");
alcDictionary.Add(alc, dl);
}
With Foreach ( It works good!)
int d = 0;
Alcohol s = null;
foreach (var item in alcDictionary)
{
if (item.Key.Equals(alc))
{
d = item.Value;
s = item.Key;
}
}
if (s != null)
{
alcDictionary[s] = d + dl;
}
else
{
alcDictionary.Add(alc, dl);
}
Some other code:
public Kocsma()
{
Upload(new Alcohol("Borsodi alc", 160, 4.6), 1000);
Upload(new Alcohol("Pilsner Urquell", 250, 4.4), 800);
Upload(new Alcohol("Soproni Ászok", 150, 4.5), 900);
Upload(new Alcohol("Dreher Classic", 200, 5.2), 600);
}
static void Main(String[] args)
{
Alcohol b = new Alcohol("Borsodi alc", 160, 4.6); //34
Alcohol c = new Alcohol("Bratista alc", 230, 4.5); // 51
Alcohol d = new Alcohol("Soproni Ászok", 150, 4.5); // 33,3
Kocsma pub = new Kocsma();
pub.Upload(c, 300);
pub.Upload(d, 450);
pub.Upload(b, 100);
}
You need to correctly override
GetHashCode()in your key class.GetHashCode()must return equal values for equal objects.