I am stumped. I need help. I have a DTO object with duplicates patient address data. I need to get only the unique addresses.
Dim PatientAddressDto = New List(Of PatientAddress)
{Populate PatientAddressDto with lots of duplicate data}
PatientAddressDto = (From d In PatientAddressDto
Group d By PatientAddressDtoGrouped = New PatientAddress With {
.Address1 = d.Address1,
.Address2 = d.Address2,
.City = d.City,
.State = d.State,
.Zip = d.Zip
}
Into Group
Select New PatientAddress With {
.Address1 = PatientAddressDtoGrouped.Address1,
.Address2 = PatientAddressDtoGrouped.Address2,
.City = PatientAddressDtoGrouped.City,
.State = PatientAddressDtoGrouped.State,
.Zip = PatientAddressDtoGrouped.Zip
}).ToList()
I have tried the following with no luck:
PatientAddressDto = (From d In PatientAddressDto
Select New PatientAddress With {
.Address1 = d.Address1,
.Address2 = d.Address2,
.City = d.City,
.State = d.State,
.Zip = d.Zip
}).Distinct
and also
PatientAddressDto = PatientAddressDto.GroupBy(Function(p) New PatientAddress With {
.Address1 = p.Address1,
.Address2 = p.Address2,
.City = p.City,
.State = p.State,
.Zip = p.Zip
})
You can use an anonymous type and make use of the Key
keyword in order for equality to behave the way you expect (not required for C#).
Change your grouping by specifying the Key
prefix and remove the PatientAddress
usage :
Group d By PatientAddressDtoGrouped = New With {
Key .Address1 = d.Address1,
Key .Address2 = d.Address2,
Key .City = d.City,
Key .State = d.State,
Key .Zip = d.Zip
}
I have found the following code to work which essentially accomplishes the grouping that I desire and populating the new object as type PatientAddress therefore eliminating the use of anonymous objects and the keyword Key.
Maybe someone can explain it, at the moment I can not. Have a nice day.
Dim PatientAddressDto = New List(Of PatientAddress)
{Populate PatientAddressDto with lots of duplicate data}
PatientAddressDto = (From d In PatientAddressDto
Group d By d.Address1,
d.Address2,
d.City,
d.State,
d.Zip Into g =
Group Let grp = New PatientAddress With {.Address1 = Address1,
.Address2 = Address2,
.City = City,
.State = State,
.Zip = Zip}
Select grp).ToList()
Its probably because PatientAddress
does not override GetHashCode
and Equals
.
An alternative is to us an anonymous type for the grouping. Try writing:
Group d By PatientAddressDtoGrouped = New With { Key .Address1 = d.Address1, ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With