Linq Group on Multiple Fields - VB.NET, Anonymous, Key

爱⌒轻易说出口 提交于 2019-11-29 01:26:04

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, ....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!