C# Linq GroupBy ==> Class vs Anonymous class --- different result

Viewed 99

I have the following code:

var rawGroupBEFORE = sqlRaw.GroupBy(x => new
{
    x.ID,
    x.P1,
    x.P2,
    x.P3,
    x.P4,
    x.P5,
    x.P6,
    x.P7,
    x.P8,              
}).ToList();

var rawGroup = sqlRaw.GroupBy(x => new RawDocument
{
    Id = x.ID,
    P1 = x.P1,
    P2 = x.P2,
    P3 = x.P3,
    P4 = x.P4,
    P5 = x.P5,
    P6 = x.P6,
    P7 = x.P7,
    P8 = x.P8,              
}).ToList();

And with the data that I have in the rawGroupBEFORE 1 element as result. In the rawGroup gives me 2 elements ..... wrong grouping. I have created the class RawDocument using the automatic Visual Studio "create missing property" action.

Any ideas why I should be getting this behavior?

1 Answers

The most likely explanation is that the anonymous type uses value equality, while RawDocument uses reference equality. Since each item will get a new RawDocument object, none of them will be equal to each other.

Implement Equality members for RawDocument, or give the GroupBy a IEqualityComparer.

Related