Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7644371
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T09:40:19+00:00 2026-05-31T09:40:19+00:00

Given the following classes: public class WeekOfYear : IEquatable<WeekOfYear>, IComparable<WeekOfYear> { private readonly DateTime

  • 0

Given the following classes:

public class WeekOfYear : IEquatable<WeekOfYear>, IComparable<WeekOfYear>
{
    private readonly DateTime dateTime;
    private readonly DayOfWeek firstDayOfWeek;

    public WeekOfYear(DateTime dateTime)
        : this(dateTime, DayOfWeek.Sunday)
    {
    }

    public WeekOfYear(DateTime dateTime, DayOfWeek firstDayOfWeek)
    {
        this.dateTime = dateTime;
        this.firstDayOfWeek = firstDayOfWeek;
    }

    public int Year
    {
        get
        {
            return dateTime.Year;
        }
    }

    public int Week
    {
        get
        {
            return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, firstDayOfWeek);
        }
    }

    public bool Equals(WeekOfYear other)
    {
        return Year == other.Year && Week == other.Week;
    }

    public int CompareTo(WeekOfYear other)
    {
        if (Year > other.Year || Year == other.Year && Week > other.Week)
        {
            return 1;
        }
        if (Equals(other))
        {
            return 0;
        }
        return -1;
    }

    public override string ToString()
    {
        return String.Format("Week of {0}", dateTime.FirstDayOfWeek(firstDayOfWeek).ToString("MMMM dd, yyyy"));
    }
}

public class WeekOfYearComparer : IEqualityComparer<WeekOfYear>, IComparer<WeekOfYear>
{
    public bool Equals(WeekOfYear x, WeekOfYear y)
    {
        return x.Equals(y);
    }

    public int GetHashCode(WeekOfYear weekOfYear)
    {
        return weekOfYear.GetHashCode();
    }

    public int Compare(WeekOfYear x, WeekOfYear y)
    {
        return x.CompareTo(y);
    }
}

This test fails (unexpectedly):

[Test]
public void Fails()
{
    var dates = new List<DateTime>
                    {
                        new DateTime(2012, 1, 1),
                        new DateTime(2012, 2, 1),
                        new DateTime(2012, 1, 1)
                    };

    IEnumerable<IGrouping<WeekOfYear, DateTime>> groups = dates.GroupBy(date => new WeekOfYear(date), new WeekOfYearComparer());

    Assert.That(groups.Count(), Is.EqualTo(2)); // count is 3
}

And this test passes (expectedly):

[Test]
public void Works()
{
    var dates = new List<DateTime>
                    {
                        new DateTime(2012, 1, 1),
                        new DateTime(2012, 2, 1),
                        new DateTime(2012, 1, 1)
                    };

    var groups = dates.GroupBy(
        date =>
            {
                var weekOfYear = new WeekOfYear(date);
                return new { weekOfYear.Year, weekOfYear.Week };
            });

    Assert.That(groups.Count(), Is.EqualTo(2));
}

Why does the first test result in a count of 3?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T09:40:21+00:00Added an answer on May 31, 2026 at 9:40 am

    The first part of an equality check is done via the hash-code; you must provide a valid hash-code implementation (for why, see Why is it important to override GetHashCode when Equals method is overridden?). Your comparer could do this, but it defers to the object:

    public int GetHashCode(WeekOfYear weekOfYear)
    {
        return weekOfYear.GetHashCode();
    }
    

    and the object does not provide a valid hash-code. A suitable implementation inside WeekOfYear would be something like:

    public bool Equals(WeekOfYear other)
    {
        return other != null && Year == other.Year && Week == other.Week;
    }
    public override bool Equals(object obj)
    {
        return Equals(obj as WeekOfYear);
    }
    public override int GetHashCode()
    { // exploit number of weeks in year
        return (Year.GetHashCode()*52) + Week.GetHashCode();
    }
    

    Noting I’ve also provided an override for equality too.

    Actually, since your object provides all the code here, there is no benefit in a custom comparer; you could remove WeekOfYearComparer completely, as the default behaviour is to look for suitable equality/comparison operations on the underlying type:

    var groups = dates.GroupBy(date => new WeekOfYear(date));
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given the following classes: class foo { private: int c; public: foo( int a
Given the following classes: public class Container { private List<SomeData> list; // public getter
Given the following classes: public class ContentItem : IEquatable<ContentItem> { ... } and public
Updated question given Andrew Hare's correct answer: Given the following C# classes: public class
Given the following two classes: public class ABC { public void Accept(Ordering<User> xyz) {
Given the following POCO classes: public class Certification { public int Id { get;
Given the following assemblage of classes (contrived): public class School { [PrimaryKey] public string
Given the following classes: public class Class1<TObject> { protected void MethodA<TType>(Expression<Func<TObject, TType>> property, ref
I have a very simply question regarding IEquatable. Given the following basic classes: public
Given the following classes... public abstract class FooBase<TBar> where TBar : BarBase{} public abstract

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.