2

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?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Dryadwoods
  • 2,875
  • 5
  • 42
  • 72
  • 2
    You are running one query after another. Are results also different if you run just one (comment either first)? Ideally you need present a proof of the problem in a form of [mcve]. – Sinatr Nov 12 '20 at 10:06
  • 2
    Does `RawDocument` overrides `GetHashCode` and `Equals`? – Svyatoslav Danyliv Nov 12 '20 at 10:07
  • @Sinatr the result is always the same if I comment or not..... or if I invert them. Its is always the same. – Dryadwoods Nov 12 '20 at 10:07
  • @SvyatoslavDanyliv No... the class is a plain DTO object with just properties like: public int Id { get; set; } – Dryadwoods Nov 12 '20 at 10:08
  • which net version is it? is the variable sqlraw already fetched data (with a tolist()) or might this be run on a sqlserver as a query? – HrkBrkkl Nov 12 '20 at 10:22

1 Answers1

9

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • 1
    or in .NET 5: record types: `public record RawDocument(int Id);` or `public record RawDocument { public int Id { get; set; } }` (the latter being mutable) – Marc Gravell Nov 12 '20 at 10:20