Some of your code doesn't much much sense, but for this code I have updated your setName
public void setName(string name)
{
Console.WriteLine("Please Enter the name of the Person");
this.name = name;
}
There is no point passing in a "name" for it to just be overriden with a console input.
Your dictionary isn't finding your object because it is searching for the actual object you are giving it
Dictionary<int, Person> dictionary = new Dictionary<int, Person>();
Person personJohn = new Person();
personJohn.setName("John");
dictionary.Add(1, personJohn);
Person personDave = new Person();
personDave.setName("Dave");
dictionary.Add(2, personDave);
Person nam = new Person();
bool success = nam.SearchPerson(dictionary, personJohn);
Person tempPerson = new Person();
tempPerson.name = "John";
success = nam.SearchPerson(dictionary, tempPerson);
You don't want your code to work at the object level though, you are only interested in matching property values, not matching objects. You can update your search function like so
public bool SearchPerson(Dictionary<int, Person> dict, Person pr)
{
if (dict.Values.Any(p => p.name == pr.name))
{
Console.WriteLine("Successfully found");
return true;
}
return false;
}
Another solution is to create a custom comparer that tells the code that two objects are equivalent if the name properties are the same.
public class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (x == null || x.name == null || y == null || y.name == null)
{
return false;
}
return x.name.Equals(y.name);
}
public int GetHashCode(Person obj)
{
return obj.name.GetHashCode();
}
}
Your search function will now look like
public bool SearchPerson(Dictionary<int, Person> dict, Person pr)
{
if (dict.Values.Contains(pr, new PersonComparer()))
{
Console.WriteLine("Successfully found");
return true;
}
return false;
}