Consider we have these two entities and one custom object :
public class Entiy1
{
public int Id { get; set; }
public int DestinationId { get; set;
You can use the LINQ join operator like this:
var results = from e1 in context.Entity1s
join e2 in context.Entity2s
on e1.DestinationId equals e2.DestinationId
select new EntityDTO
{
DestinationId = e1.DestinationId,
Name = e1.Name,
JobTitle = e1.JobTitle,
DestinationName = e2.DestinationName
};
Using LINQ extensions, I'm more of a fan of them:
var results = entityList1
.GroupBy(e => e.DestinationId)
.Select(e => e.First())
.Join(entityList2, e1 => e1.DestinationId, e2 => e2.DestinationId, (e1, e2) =>
new EntityDTO
{
DestinationId = e1.DestinationId,
DestinationName = e2.DestinationName,
JobTitle = e1.JobTitle,
Name = e1.Name
});
Same thing as Gert's anwser really. You can use Distinct
but, you would have to inherit from IEquatible<T>
and implement the Equals
method and override the GetHashCode
method to get it to work.
Here's a way to do it:
var query = from e1 in
(from e1 in entities1
group e1 by e1.DestinationId into grp
select grp.First())
join e2 in entities2 on e1.DestinationId equals e2.DestinationId
select new EntityDTO
{
DestinationId = e1.DestinationId,
DestinationName = e2.DestinationName,
Name = e1.Name,
JobTitle = e1.JobTitle
} ;
The trick is the group by
and then taking the first element of the grouping. This is also referred to as "distinct by" that a library like MoreLinq provides out of the box.