Code Fragment

Code Fragment

  • NA
  • 2
  • 582

Interview question 1 - Better way to write the below code

Jul 17 2020 1:11 PM
I have a Person Class with 1 property called Name, i have a class called Pet with 2 properties Name and Owner
 
I have list of persons and list of Pets, i wrote this code to print all the persons and mention whether they have a pet or not. 
 
This code works fine, i just wanted to check if there is a better way to write this 
 
class Pet
{
public string Name {get;set;} 
public string Owner {get;set;} 
}
 
class  Person
{
public string Name {get;set;} 
 
public static void Print()
{
List<Person> Persons = new List<Person>()
{
  new Person {Name = "V1"}, new Person {Name = "V2"}, new Person {Name = "V3"}
};
List<Pet> Pets = new List<Pet>()
{
new Pet {Name = "P1", Owner = "V1"}, new Pet {Name = "P3", Owner = "V3"}
};
 
foreach(Person p in Persons)
{
Pet pObj = Pets.Where(a => a.Owner == p.Name).FirstOrDefault(); 
if(pObj != null)
{
Console.WriteLine(p.Name + " Has a pet");
else
{
Console.WriteLine(p.Name + " Does not have a pet"); 

Answers (2)