How can I check if an object exists in the dictionary and return it

4

I am working on a solution where I have to enter the same function with a given name of a Park. The parks are implemented in a list and each park has a name. It happens that I intend and already tried to develop a function in which when searching a park it must be returned (written) or should appear a message similar to "It was not found".

I'm working in C # layers (which is where I'm developing the app) and in DL (Data Layer) I have a dictionary of Park , class that has on it a List of Automoveis , and a list of ParkedAuto which corresponds to a set of cars parked in a park.

Here is the method I have in DL:

 public static bool DevolveParque(string fileName, string nomeParque)
        {
            if (File.Exists(fileName))
            {
                try
                {
                    Stream stream = File.Open(fileName, FileMode.Open);
                    BinaryFormatter bin = new BinaryFormatter();
                    parques = (Dictionary<string, Park>)bin.Deserialize(stream);
                    stream.Close();
                    return true;


                }
                catch (IOException e)
                {
                    Console.Write("ERRO:" + e.Message);

                }


                foreach (KeyValuePair<string, Park> x in parques)
                {

                    if (parques.ContainsKey(nomeParque))
                    {
                         Console.WriteLine("Nome: " + x.Key);
                    }
                }
            }
            return false;

        }

If you have repaired it right here, I will testo with a decisive instruction, ( if ), if my parks have a key that corresponds to the park name, existing in the Parks Dictionary ( static Dictionary<string, Park> parques = new Dictionary<string, Park>(); )

When debugging the program that is running the key (which by definition corresponds to the name of the park) but does not show the park, nor does it tell me that it was not found.

How can I change this.

Note: I am working with files (files), they have Parks and also have several vehicles inside the parks

    
asked by anonymous 26.06.2015 / 00:10

1 answer

2

Change the excerpt:

foreach (KeyValuePair<string, Park> x in parques)
{
    if (parques.ContainsKey(nomeParque))
    {
         Console.WriteLine("Nome: " + x.Key);
    }
}

To

if(parques.ContainsKey(nomeParque)) {
    Park park = parques[nomeParque];
    Console.WriteLine(/* Imprimir aqui o que quer do objeto park*/);
}   
else {
    Console.WriteLine("Não encontrado!");
}

There is no reason to iterate through the dictionary items, since the key is unique, just check if it exists and get its value, in this case the Park object. But that's assuming your dictionary has loaded properly.

    
26.06.2015 / 00:19