Reputation: 545
I need to join two lists by an Id in order to map values to an User entity.
For that part, I think I've managed to do it with :
var concernedParticipantIds = baseValues.Select(x => x.ParticipantId).Distinct().ToList();
var queryParticipants =_unitOfWorkMt.GetMTReadonly<Participant>().GetQuery(tenantId).Where(x => concernedParticipantIds.Contains(x.Id));
var participantAndValues = from value in baseValues
join participant in queryParticipants on value.ParticipantId equals participant.Id
select new {Participant = participant, Value = value};
But it results in one line per Value like this :
user_1 => value_1
user_1 => value_2
user_1 => value_3
user_2 => value_1
user_2 => value_2
user_2 => value_3
...
Is there a way to group by the user? I'd like something like :
- user_1 => value_1
value_2
value_3
- user_2 => value_1
value_2
value_3
The only thing I came up with is something like
var results = from p in participantAndValues
group p.Value by p.Participant into temp
select new { Person = temp.Key, Values = temp.ToList() };
Seems to work but not sure it's the right way, and maybe there's a way to do it in one query?
Upvotes: 0
Views: 42
Reputation: 26926
Use GroupJoin
:
var participantAndValues = from value in baseValues
join participant in queryParticipants on value.ParticipantId equals participant.Id into paricipantJ
select new {Participant = participant, Values = participantJ };
Upvotes: 1
Reputation: 14228
You can achieve it like this way
var results = from p in participantAndValues
group p by p.Participant into g
select new { Person = g.Key, Values = g.ToList() };
Or as a non-query expression:
var results = participantAndValues.GroupBy(p => p.Participant)
.Select(g => new { Person = g.Key, Values = g.ToList() });
Upvotes: 1