Reputation: 2049
Consider we have these two entities and one custom object :
public class Entiy1
{
public int Id { get; set; }
public int DestinationId { get; set; }
public string Name { get; set; }
public string JobTitle { get; set; }
}
public class Entiy2
{
[Key]
public int DestinationId { get; set; }
public int DestinationName { get; set; }
}
public class EntityDTO
{
public int DestinationName { get; set; }
public int DestinationId { get; set; }
public string Name { get; set; }
public string JobTitle { get; set; }
}
Data is something like this :
Entity1 :
Id=1 , DestinationId=1,Name=Name1,JobTitle=Job1
Id=2 , DestinationId=1,Name=Name2,JobTitle=Job2
Id=3 , DestinationId=2,Name=Name3,JobTitle=Job3
Id=4 , DestinationId=2,Name=Name4,JobTitle=Job4
Id=5 , DestinationId=2,Name=Name5,JobTitle=Job5
Entity 2:
DestinationId=1 , DestinationName=Destination1
DestinationId=2 , DestinationName=Destination2
How can I select distinct destinationId and select Name and JobTitle from Entity1 then join them with Entity2 to fetch destination name and returning them as EntityDTO ?
Upvotes: 1
Views: 9567
Reputation: 3397
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.
Upvotes: 3
Reputation: 109137
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.
Upvotes: 3
Reputation: 26863
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
};
Upvotes: 0