I have the below
public class Person
{
// Properties
public string Name { get; set; }
public string Area { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public List<Person> GetPersonData()
{
List<Person> personLst = new List<Person> {
new Person { Name="Shashidhar Niketani", Age=20, Gender="Male" , Area = "Assam"},
new Person { Name="Ahmed Ali Khan", Age=25 ,Gender="Male", Area = "Assam" },
new Person { Name="S. Mirja", Age=20, Gender="Female", Area = "Assam"},
new Person { Name="Neru Kumar", Age=18, Gender="Female", Area = "Colombo"},
new Person { Name="Chidam P", Age=19, Gender="Male", Area = "Colombo"},
new Person { Name="H Kontala", Age=19, Gender="Male", Area = "Bombay"},
new Person { Name="Priya Pankhraj", Age=23, Gender="Female", Area = "North Punjab"},
new Person { Name="Ambla", Age=20, Gender="Female", Area = "Madras"},
new Person { Name="H Kontala", Age=25, Gender="Male", Area = "Bombay"},
new Person { Name="Sirisha Chalukuri", Age=30, Gender="Female", Area = "Bombay"}};
return personLst;
}
public override string ToString()
{
return string.Format("Patient Name: = {0} , Age:= {1}, Gender:= {2}, Area: = {3}", Name, Age, Gender, Area);
}
}
public class Hobbies
{
public string Owner { get; set; }
public string HobbyName { get; set; }
public List<Hobbies> GetHobbies()
{
List<Hobbies> hobbyList = new List<Hobbies> {
new Hobbies { Owner="Sirisha Chalukuri", HobbyName = "Singing"},
new Hobbies { Owner="Priya Pankhraj", HobbyName = "Cooking" },
new Hobbies { Owner="S. Mirja", HobbyName="Playing"},
new Hobbies { Owner="Neru Kumar", HobbyName="Programing"}};
return hobbyList;
}
}
I am trying to perfom a left join
//fetch those records
Person p = new Person();
var personSource = p.GetPersonData();
Hobbies h = new Hobbies();
var hobbySource = h.GetHobbies();
//Left outer join
var res8 = (from person in personSource
join hobby in hobbySource
on p.Name equals hobby.Owner into temp
from hobby in temp.DefaultIfEmpty()
select new
{
PersonName = p.Name,
PersonAge = p.Age,
Gender = p.Gender,
LivesIn = p.Area,
Hobby = (hobby == null) ? "N/A" : hobby.HobbyName
});
But I am not able to get the correct result…All the records are coming as null/non matching records..There are atleast 4 matching records and the rest will be non-matching records…
I am rather looking for like given these two datasource, the result that we will expect if we perform a left join on PersonName and HobbyOwner.
Help needed
When you reference hobby.HobbyName in your select projection, hobby is null when there are no matching hobbies for a person (DefaultIfEmpty returns null for an empty hobby collection). You need to check if hobby is null, and if so assign the Hobby property in the select projection a default value. For example:
Also, don’t know if it was a typo, but in your query you use p when you should be using person: