Link to home
Start Free TrialLog in
Avatar of Alejandro A
Alejandro AFlag for United States of America

asked on

At least one object must implement IComparable. - Sorting a GroupedCollection with Linq

I have the following structures as example:

class ServicesGroup : IServicesGroup, IComparable
{
      public string CityName { get; set; }
      public ObservableCollection<Service> Services { get; set; }
      public int CompareTo(object obj)
    {
        ServicesGroup sg = (ServicesGroup)obj;

        return String.Compare(this.CityName, sg.CityName);
    }            
}

I am trying to sort my collection of Services at each group by its [ServiceId] (ascending and descending):

tempCollection = new ObservableCollection<object>(collection.OrderBy(x => ((ServicesGroup)x).Services.OrderBy(y => y.ServiceId)));

My Service class implements IComparable as well:

I tried both
public class Service : IComparable, IEquatable
public class Service : IComparable<Service>, IEquatable<Service>

Example of my Service class:

public class Service : IComparable, IEquatable
{
            public string ServiceId {get; set;}
       

        public string ServiceType {get; set;}
           
            public int CompareTo(object obj)
        {
            Service s = (Service)obj;

            return String.Compare(this.ServiceId, s.ServiceId);
        }
       
            public bool Equals(Service other)
        {
            if (this.ServiceId.Equals(other.ServiceId) && this.ServiceType.Equals(other.ServiceType)) return true;
            return false;
        }            
}

When I try to run my linq I get the following error:

Additional information: At least one object must implement IComparable.

I can not access the [public ObservableCollection<Service> Services] for some reason. What am I missing here?
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alejandro A

ASKER

Thank you so much for your help James