简体   繁体   中英

How to left outer join for two unequal lists in linq

What I mean by two unequal lists is:

LIST 1:

LeaveType  Openning
---------  --------
Casual        25
Annual        30
Medical       23

LIST 2:

LeaveType  Availed
---------  -------
Casual       3
Annual       5

Notice that the two lists above have unequal number of rows, I'm trying to combine the above two lists through an identical column ie LeaveType by left joining the two lists to get the result as below:

OUTPUT LIST:

LeaveType  Openning  Availed
---------  --------  -------
Casual        25        3
Annual        30        5
Medical       23        0

What I've tried so far is the below linq query:

(from o in LIST1
  join a in LIST2
  on o.LeaveType equals a.Leave_Type
  into temp
  from a in temp.DefaultIfEmpty()
  select new
  {
     LeaveType = o.LeaveType,
     Openning = o.Openning,
     Availed = a.Availed == 0 ? 0 : a.Availed,         
  }).ToList();

The above query works fine for creating the first two rows of the output list but when it comes for about creating the third row, it throws NullReferenceException , even if I put the check as a.Availed == 0 ? 0 : a.Availed a.Availed == 0 ? 0 : a.Availed to return zero, the a.Availed is of type decimal , but still it throws the NullReferenceException , Why? and how to get rid of this? Thanks :)

Edit

NullReferenceException just for evidence:

在此处输入图片说明

You need to check if 'a' is null everytime you want to access a property of that item because it will be null (by default) if it is empty. In other words, when you call DefaultIfEmpty() you are doing a left join relative to the first list (LIST1 in your case). This means that 'a' will be null if there is no match with your join match clause (o.LeaveType equals a.LeaveType in your case).

select new
{
    LeaveType = o.LeaveType,
    Openning = o.Openning,
    Availed = a == null ? 0 : a.Availed, //check if a is null  
    Balance = o.Openning - a == null ? 0 : a.Availed //check if a is null       
}).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM