Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At least one object must implement IComparable

var listair = empcon.OrderBy(x => x.CustomerConnection.OrderBy(y => y.Id)).ToList();

When I am using this statement then I am getting exception "At least one object must implement IComparable"

How can I solve this problem?

like image 957
Amit Avatar asked Jun 24 '11 11:06

Amit


People also ask

How do you implement IComparable interface?

It requires that implementing types define a single method, CompareTo(Object), that indicates whether the position of the current instance in the sort order is before, after, or the same as a second object of the same type. The instance's IComparable implementation is called automatically by methods such as Array.

How does IComparable work C#?

C# IComparable interfaceThe IComparable interface defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances. The IComparable is implemented by types whose values can be ordered or sorted. The interface requires the CompareTo method to be implemented.

What is the purpose of IComparable interface?

The IComparer interface is used to sort elements that compare two objects and provides additional comparison method.

What is the difference between IComparer and IComparable in C#?

IComparer compares two objects that it's given. IComparable is implemented by the object that is being compared, for the purpose of comparing with another one of itself.


2 Answers

I had this problem with my query when I wrote it wrong:

IEnumerable<OrgRelation> relations = from r in tree.OrgRelations
                                                 orderby r.ParentUnit, r.ChildUnit
                                                 select r;

This was because the Parent and Child Units are both OrgUnit objects the are related to this OrgRelation entity. What I needed was to order not by the object, but by the property of the object on which I really wanted to sort. When I added the ".Name" it worked.

IEnumerable<OrgRelation> relations = from r in tree.OrgRelations
                                                 orderby r.ParentUnit.Name, r.ChildUnit.Name
                                                 select r;
like image 69
Joey Morgan Avatar answered Sep 19 '22 14:09

Joey Morgan


Implement IComparable for the Types of the objects contained by CustomerConnection and empcon. If they don't have IComparable implemented then there is no way to perform an order by.

like image 26
Jeff Machamer Avatar answered Sep 16 '22 14:09

Jeff Machamer