Craig Curtis
Craig Curtis

Reputation: 863

Why do typed and anonymous key selectors in GroupBy produce different results?

I don't know why I am getting different results for the two following GroupBy() queries. I'd expect them to both return 3 groupings, but the typed key selector GroupBy() returns 4.

Given a key class:

class Key
{
    public int Day { get; set; }
}

When I run:

var data = new[]
{
    new { Date = DateTime.Now },
    new { Date = DateTime.Now },
    new { Date = DateTime.Now.AddDays(1) },
    new { Date = DateTime.Now.AddDays(2) }
};

var groupsByAnonymousKey = data.GroupBy(m => new
{
    m.Date.DayOfYear
});

var groupsByTypedKey = data.GroupBy(m => new Key
{
    Day = m.Date.DayOfYear
});

var anonymousCount = groupsByAnonymousKey.Count(); // 3
var typedCount = groupsByTypedKey.Count();         // 4

anonymousCount is 3 and typedCount is 4.

Upvotes: 0

Views: 235

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13498

Because at second variant you group by class: Key. Class instances not equal each other, even if all their properties are equal, instead of anonumous types. So typedCount always will be equal data.Length. To fix it, you can specify comparer at another versions of GroupBy operator or override Equals and GetHashCode methods of Key class, also you can change Key class to struct.

Upvotes: 2

Related Questions