Consider the following code, where I have flattened list of application-and-owner pairs, applicationAndOwnerPairs
:
var applications = _mapper.Map<List<Application>>(untaggedGraphApplications);
var applicationAndOwnerPairs = applications.SelectMany(a => a.Owners, (a, o) => new { a, o }).ToList();
var applicationsByOwner = applicationAndOwnerPairs.GroupBy(ao => ao.o.Id, ao => ao, (key, g) => new { ownerId = key, applications = g.ToList() }).ToList();
I want to group these pairs by the owner ID, and for each group create a result with the ownerId
, owner
, and owned applications
.
However, the resultSelector
only gives me access to the key and the applications, not the owner corresponding to the key.
Is there a way to get access to the owner within groupBy
, or do I need to create a map mapping owner IDs to owners prior to executing groupBy
?
1
You could group by owner
instead of ownerId
, and give GroupBy an IEqualityComparer<owner>
that compares the object by the key. I.e.
public class OwnerIdEquality : IEqualityComparer<owner>{
public bool Equals (T? x, T? y) => x?.Id == y?.Id;
public int GetHashCode (T obj) => obj.Id.GetHashCode();
}
You can work by extracting the first Owner
and list of Applications
for each group as below:
var applicationAndOwnerPairs = applications
.SelectMany(a => a.Owners,
(a, o) => new
{
Application = a,
Owner = o
})
.ToList();
var applicationsByOwner = applicationAndOwnerPairs
.GroupBy(ao => ao.Owner.Id,
ao => ao,
(key, g) => new
{
OwnerId = key,
Owner = g.First().Owner,
Applications = g.Select(x => x.Application).ToList()
})
.ToList();