I am struggling with linq (left join - group - count). Please help me. Below is my code and it gives me this result.
Geography 2 Economy 1 Biology 1
I expect this ...
Geography 2 Economy 1 Biology 0
How can i fix this?
class Department { public int DNO { get; set; } public string DeptName { get; set; } } class Student { public string Name { get; set; } public int DNO { get; set; } } class Program { static void Main(string[] args) { List<Department> departments = new List<Department> { new Department {DNO=1, DeptName="Geography"}, new Department {DNO=2, DeptName="Economy"}, new Department {DNO=3, DeptName="Biology"} }; List<Student> students = new List<Student> { new Student {Name="Peter", DNO=2}, new Student {Name="Paul", DNO=1}, new Student {Name="Mary", DNO=1}, }; var query = from dp in departments join st in students on dp.DNO equals st.DNO into gst from st2 in gst.DefaultIfEmpty() group st2 by dp.DeptName into g select new { DName = g.Key, Count = g.Count() }; foreach (var st in query) { Console.WriteLine("{0} \t{1}", st.DName, st.Count); } } }
source share