Linq join iquery, how to use defaultifempty

86,863

You basically want to do a left outer join. The way you currently are using the DefaultIfEmpty method is that if the entire list is empty you provide a single default entry.

You should join with PassengerDetails and for each passenger details list call the default if empty. This is the equivalent of a left outer join and it goes a little something like this:

var data = from fd in FlightDetails
           join pd in PassengersDetails on fd.Flightno equals pd.FlightNo into joinedT
           from pd in joinedT.DefaultIfEmpty()
           select new {
                         nr = fd.Flightno,
                         name = fd.FlightName,
                         passengerId = pd == null ? String.Empty : pd.PassengerId,
                         passengerType = pd == null ? String.Empty : pd.PassengerType
                       }
Share:
86,863
user1032957
Author by

user1032957

Updated on May 16, 2020

Comments

  • user1032957
    user1032957 about 4 years

    I have written a linq join query and I would like to take the values, if one of them are empty...

    Code:

    var Details = 
    
    UnitOfWork.FlightDetails
              .Query()
              .Join
              (
                  PassengersDetails,
                  x => x.Flightno,
                  y => y.FlightNo,
                  (x, y) => new
                  {
                      y.PassengerId,
                      y.classType,
                      x.Flightno,
                      x.FlightName,
                  }
              );
    

    I would like to use something like..

    "Above query".DefaultIfEmpty
    (
        new 
        {
            y.PassengerId,
            y.classType,
            string.Empty,
            string.Empty
        }
    );
    

    FlightDetails is Idatarepository type on a class and PassengerDetails is IQueryable local variable result. How can I get result with PassengerId and Classtype without flightno and flightname included in the overall results?