41

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?

Mark Cooper
  • 6,738
  • 5
  • 54
  • 92
user1032957
  • 453
  • 1
  • 6
  • 16
  • I am not sure if `DefaultIfEmpty()` will work with anonymous methods. Try defining a class and using that. – Sam Leach Oct 10 '13 at 11:00
  • You are looking for the syntax of a "Left Outer Join" which has been answered in other questions. Here is the top one for Method/Lambda LINQ syntax: http://stackoverflow.com/questions/584820/how-do-you-perform-a-left-outer-join-using-linq-extension-methods – Ocelot20 Oct 10 '13 at 11:02

1 Answers1

85

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
                       }
Ben
  • 54,723
  • 49
  • 178
  • 224
Kristof
  • 3,267
  • 1
  • 20
  • 30