0

i am trying to make left outer join for two lists where i am getting NullReference Exception.I am wondering why? Please help.

I have defined my sql query at the top(Comments) which works grea in sql server for the same joint but when i represented that query to LINQ it gives me error.

ContactList Having Data as

ContactId   GroupId    FirstName    LastName    Phone    Email

enter image description here

GroupList Having Data as

GroupId   GroupName

enter image description here

Here is the query i am trying for Left Outer Join.

       /*
       * select g.Id as 'Group Id',g.Name as 'Group Name',c.Id as 'Contact Id',
       c.FirstName,c.LastName,c.Phone,c.Email from Groups g left outer join Contacts c 
       on g.Id = c.GroupId 
       */
     var joinedList1 = (from g in lstAllGroups.AsEnumerable()
                        join c in lstAllContacts.AsEnumerable()
                        on  g.GroupId equals c.GroupId  into temp
                        from rg in temp.DefaultIfEmpty()
                        orderby g.GroupId
                        select new 
                        {
                           GroupId = g.GroupId,
                           GroupName = g.GroupName,
                           ContactId = rg.ContactId == null ? 0 : rg.ContactId,
                           FirstName=rg.FirstName == null ?String.Empty: rg.FirstName,
                           LastName = rg.LastName == null ? String.Empty : rg.LastName,
                           Phone = rg.Phone == null ? String.Empty : rg.Phone,
                           Email = rg.Email == null ? String.Empty : rg.Email,
                         }).ToList();

    foreach (var item in joinedList1)
    {
         Console.WriteLine(item);
    }

Note : In Left Outer Join, GroupList is the first Datasource and ContactList is the second datasource.

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
  • Group 14 has no match, so `rg` will be null and `rg.ContactId` (among others) will throw an exception. – D Stanley Mar 24 '15 at 02:45
  • @DStanley - Thanks but how can i solve this? What modification i should do in the code. Please help – Chandan Kumar Mar 24 '15 at 06:32
  • Do you want a left join? Or just an inner join? If you want a left join what do you want to output if `rg` is null? – D Stanley Mar 24 '15 at 12:44
  • @DStanley - how can i check if "rg" is null or not? i am checking like this "ContactId = rg.ContactId == null ? 0 : rg.ContactId," for the fields...not the "rg". how can i achieve this ? – Chandan Kumar Mar 25 '15 at 05:45
  • 1
    `ContactId = rg == null ? 0 : rg.ContactId`. Review the "duplicate" question to better understand how to deal with null reference exceptions. – D Stanley Mar 25 '15 at 14:12

0 Answers0