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?
The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source.
The DefaultIfEmpty() method returns a new collection with the default value if the given collection on which DefaultIfEmpty() is invoked is empty. Another overload method of DefaultIfEmpty() takes a value parameter that should be replaced with default value.
DefaultIfEmpty<TSource>(IEnumerable<TSource>) Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.
A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group join.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With