Search code examples
vb.netlinqleft-joinlinq-group

LINQ nested grouping with multiple collections


I am currently struggling to assemble a LINQ query on my objects collections : Persons, Cars

Each person can have multiple cars.

I want to select all PERSONS in persons and all group all cars owned by this person. The query I have written so far is:

from c in persons,d in cars 
    where c.id = d.ownerID 
    group by c.Firstname into MG = tolist() 

but it only returns persons who have cars. If a person does not have car, he is not in list. I cannot make up with the right logic.


Solution

  • try:

    List<person> plist = new List<person>();
            plist.Add(new person(1, "a"));
            plist.Add(new person(2, "b"));
            plist.Add(new person(3, "c"));
            plist.Add(new person(4, "d"));
    
            List<cars> clist = new List<cars>();
            clist.Add(new cars(1, "c1"));
            clist.Add(new cars(1, "c2"));
            clist.Add(new cars(1, "c5"));
            clist.Add(new cars(2, "c1"));
            clist.Add(new cars(3, "c1"));
            clist.Add(new cars(3, "c5"));
            clist.Add(new cars(3, "c3"));
            clist.Add(new cars(3, "c2"));
            clist.Add(new cars(4, "c2"));
            clist.Add(new cars(4, "c5"));
    
    
            var result = from p in plist
                    join c in clist on p.id equals c.ownerID into k
                    from s in k.DefaultIfEmpty()
                    select new { p.firstName , carName = (s == null ? String.Empty :s.name)};
    
    string sss = "";
     foreach (var v in result)
     {
          sss+= ( v.firstName + " : " + v.carName +  " >> "+"\n");
     }
     textBox1.Text = sss;
    

    and classes are :

    class person
    {
        public int id;
        public string firstName;
    
        public person(int id1, string name)
        {
            id = id1;
            firstName = name;
        }
    }
    
    class cars
    {
        public int ownerID;
        public string name;
    
       public cars(int id,string name1)
        {
            ownerID = id;
            name = name1;
        }
    }