Reputation: 5846
I am trying to select rows from a table. I need to perform a GroupBy on one column and then execute Distinct() on a different column. I would like to return entire rows in the results.
Assuming a database table has the following structure and data:
GroupId = 1, To = "A", From = "B", Flag = True
GroupId = 1, To = "A", From = "C", Flag = True
GroupId = 1, To = "B", From = "A", Flag = True
GroupId = 1, To = "B", From = "C", Flag = False
GroupId = 1, To = "C", From = "A", Flag = True
GroupId = 1, To = "C", From = "B", Flag = True
GroupId = 2, To = "A", From = "B", Flag = True
GroupId = 2, To = "B", From = "C", Flag = True
GroupId = 2, To = "C", From = "A", Flag = True
GroupId = 2, To = "D", From = "C", Flag = True
GroupId = 2, To = "D", From = "A", Flag = False
GroupId = 2, To = "A", From = "B", Flag = True
The following line of code returns an array of Groups with each containing an array of To
strings:
var test = db.LookupMap
.Where(u => u.Flag == true)
.GroupBy(u => u.GroupId, (key, group) => group.Select(m => m.To).Distinct())
.ToArray();
I can get an array of objects by changing m.To
to m
:
.GroupBy(u => u.GroupId, (key, group) => group.Select(m => m).Distinct())
But this breaks Distinct() on the To column.
How can I return an array of objects (entire row) instead of an array strings?
Note: The To column should be distinct per unique GroupId
Upvotes: 1
Views: 971
Reputation: 125630
Use another GroupBy
combined with First
:
.GroupBy(u => u.GroupId,
(key, group) => group.GroupBy(m => m.To).Select(g => g.First()))
It groups items without first group using To
property value and then takes first item from every inner group. It's the easiest way to get something equivalent to DistinctBy
method from moreLINQ - get whole row, but Distinct
should run only on one property values.
Upvotes: 1