Avinash
Avinash

Reputation: 633

orderby function giving exception as "at least one object must implement icomparable" when i have a List<> in another List<>

I have a Classes like this:

Public class ClassA
{

public Class1[] Class1{ get; set; }

}

Public class Class1
{

public Class2[] Class2{ get; set; }
public double TotalTime1 { get; set; }

}

Public class Class2
{

public double Count{ get; set; }

}

here i am trying to sort the ClassA like below:

IList<Class1> Data = new List<Class1>();
Data = ClassA.Class1.OrderBy(m => m.Class2.OrderBy(k => k.Count)).ToList();

Please how can i sort the Class1 using the Count in Class2.

Upvotes: 2

Views: 1402

Answers (2)

Guffa
Guffa

Reputation: 700562

You are trying to sort on the result of the inner OrderBy, which is a sequence of Class2 objects and this doesn't implement IComparable.

You have to sort on a single value, not a sequence. If you for example want to sort on the largest Count value in each Class1 object, use the Max method:

IList<Class1> Data =
  ClassA.Class1.OrderBy(m => m.Class2.Max(k => k.Count)).ToList();

There are also other plausible ways that you may want to produce a value from the Class2 array, like for example using the Min, Sum, Average or First method.

Upvotes: 1

Oded
Oded

Reputation: 499132

The compiler and LINQ do not know how either Class1 or Class2 should be ordered - how are objects of these types compare to each other.

You need these classes to implement IComparable and IComparable<T> so these kinds of objects can be compared with each other - these interfaces are used for ordering.

Upvotes: 0

Related Questions