Answered IEnumerable Distinct comparer example

  • Wednesday, April 09, 2008 12:47 AM
     
     

    I'm having trouble implementing an explicit comparer for the distinct method.

    I have an expression defined in AddressResults that returns a list of address from an in-memory object list of type <Addresses>.    I want to return a distinct list of addresses

     

    Here is some example code:

     

    var results = (from p in AddressResults
                        select p).Distinct(new AddressComparer<Addresses>());


       public class AddressComparer : IEqualityComparer<Addresses>
        {
            public bool Equals(Tester x, Addresses y)
            {
                if (x.address == y.address && x.zip == y.zip)
                    return true;
                return false;
            }

            public int GetHashCode(Addresses a)
            {
                string z = a.address+a.zip;
                return (z.GetHashCode());
            }
        }

    I am getting a compile error:

    The non-generic type AddressComparer  cannot be used with type arguments

    on the var results... line. 

     

    What am I doing wrong?

All Replies

  • Wednesday, April 09, 2008 2:32 AM
     
     Answered
    Jeff:

    You've already specified the generic type parameter you need when you derived from IEqualityComparer<Addresses>. AddressComparer doesn't need a type param, so just remove the type param when you construct the comparer. For example:

    var results = (from p in AddressResults
     
                  select p).Distinct(new AddressComparer());


    Hope that helps,
  • Thursday, April 10, 2008 4:23 AM
     
     
    Hi there.
    The compiler is right. You are creating an instance of a non generic type (AddressComparer) as if it is generic. Just Change this line of code:

    Code Snippet

    var results = (from p in AddressResults
                        select p).Distinct(new AddressComparer());


    You also have a slight mistake in the Equal signature. The parameter x must be of type Addresses too.

    Cheers.