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 3974150
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T04:32:04+00:00 2026-05-20T04:32:04+00:00

I’ve developed a generic PropertyEqualityComparer that works fine, but I’m not sure I’ve done

  • 0

I’ve developed a generic PropertyEqualityComparer that works fine, but I’m not sure I’ve done it in the right way, so if some of who can improve the code, or critic, he’s welcome.

Note : Property should implement IEquatable if is a Reference type.

    public sealed class PropertyEqualityComparer<T> : IEqualityComparer<T>
{
    private readonly Type _iequatable = Type.GetType("System.IEquatable`1", false, true);
    private readonly PropertyInfo _property;

    public PropertyEqualityComparer(string property)
    {
        PropertyInfo propInfos = typeof(T).GetProperty(property);
        if (propInfos == null)
        {
            throw new ArgumentNullException();
        }

        // Ensure Property is Equatable (override of HashCode)
        if (propInfos.PropertyType.IsValueType
            || (!propInfos.PropertyType.IsValueType
                && propInfos.PropertyType.GetInterfaces().Any(type => type.Name == _iequatable.Name)))
        {
            _property = propInfos;
        }
        else
        {
            throw new ArgumentException();
        }
    }

    public bool Equals(T x, T y)
    {
        var xValue = _property.GetValue(x, null);
        var yValue = _property.GetValue(y, null);

        return xValue.Equals(yValue);
    }

    public int GetHashCode(T obj)
    {
        return _property.GetValue(obj, null).GetHashCode();
    }
}

I’ve created two classes to see if works and all is fine, here are the classes :

public sealed class A
{
    private string _s1;
    private B _b;

    public A(string s1, B b)
    {
        _s1 = s1;
        _b = b;
    }

    public string S1
    {
        get { return _s1; }
        set { _s1 = value; }
    }

    public B B
    {
        get { return _b; }
        set { _b = value; }
    }
}

public sealed class B : IEquatable<B>
{
    private string _s;

    public string S
    {
      get { return _s; }
      set { _s = value; }
    }

    public B(string s)
    {
        S = s;
    }

    public override int GetHashCode()
    {
        return S.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as B);
    }

    public bool Equals(B other)
    {
        return (other == null)
            ? false
            : this.S == other.S;
    }
}

And the test code :

B b = new B("baby");
A[] __a = { new A("first", b), new A("second", b), new A("third", b)};
PropertyEqualityComparer<A> aComparer = new PropertyEqualityComparer<A>("B");

var vDistinct = __a.Distinct(aComparer).ToArray();
// vDistinct = __a[0] { first, baby }
var vContains = __a.Contains(new A("a", new B("baby")), aComparer);
// True
vContains = __a.Contains(new A("b", new B("foobar")), aComparer);
// False

Is here something to improve?

Thanks !

  • 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-20T04:32:04+00:00Added an answer on May 20, 2026 at 4:32 am

    Since the type of T must be known at compile-time there’s no need to pass the property name as a string. You could pass a delegate to perform type-safe, fast member access instead of brittle, slow reflection:

    var comparer = new ProjectionEqualityComparer<A, B>(a => a.B);
    
    // ...
    
    public sealed class ProjectionEqualityComparer<TSource, TKey>
        : EqualityComparer<TSource>
    {
        private readonly Func<TSource, TKey> _keySelector;
        private readonly IEqualityComparer<TKey> _keyComparer;
    
        public ProjectionEqualityComparer(Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer = null)
        {
            if (keySelector == null)
                throw new ArgumentNullException("keySelector");
    
            _keySelector = keySelector;
            _keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;
        }
    
        public override bool Equals(TSource x, TSource y)
        {
            if (x == null)
                return (y == null);
    
            if (y == null)
                return false;
    
            return _keyComparer.Equals(_keySelector(x), _keySelector(y));
        }
    
        public override int GetHashCode(TSource obj)
        {
            if (obj == null)
               throw new ArgumentNullException("obj");
    
            return _keyComparer.GetHashCode(_keySelector(obj));
        }
    }
    

    And if you really need to enforce the IEquatable<T> rule then you can just add a where TKey : IEquatable<TKey> generic constraint, but it really shouldn’t be necessary. The use of EqualityComparer<TKey>.Default should take care of all that for you, or you can pass in a custom IEqualityComparer<TKey> implementation if you prefer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I'm not entirely sure how I managed to jack this up. http://pretty-senshi.com If you
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,

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.