At least one object must implement IComparable?

asp.net-mvc dynamic-linq linq

Question

Model:

return (from m in meterReadings
       group m by new { date = m.ReadDate } into g
       select new
       {
           ReadDate = g.Key.date.ToString("dd.MM.yyyy - HH:mm:ss"),
           T1 = from t1 in g
                where t1.Name == "T1"
                select t1.Value.ToString("0,0.000"),
           T2 = from t2 in g
                where t2.Name == "T2"
                select t2.Value.ToString("0,0.000"),
           T3 = from t3 in g
                where t3.Name == "T3"
                select t3.Value.ToString("0,0.000"),
           Total = from total in g
                where total.Name == "Toplam"
                select total.Value.ToString("0,0.000")
       }).AsQueryable<object>();

Query

var table = MeterReadingManager.GetMeterReadingsPivot(meterReadings, 1);
//No Error (in title)
rows = table.OrderBy("ReadDate","desc").Skip((pageIndex) * pageSize).Take(pageSize)
//Error  (in title)
rows = table.OrderBy("T1","desc").Skip((pageIndex) * pageSize).Take(pageSize)

When I order by ReadDate, It works. But When I try to order by other fields I get the error : At least one object must implement IComparable

Why I get this error? And How can I fix it?

1
3
11/28/2012 12:35:00 PM

Accepted Answer

If you want to sort a list of items of any type, the type must implement IComparable for the sort algorithm to be able to compare items. T1 is an IQueryable, whcih does not implement IComparable. I think you intended to create string values for T1, T2, and T3. If so, you should add FirstOrDefault() to each linq statement creating T1, etc.

Edit

(After your comment)

I mean this:

T1 = (from t1 in g
     where t1.Name == "T1"
     select t1.Value.ToString("0,0.000")).FirstOrDefault()

Now T1 is a string and, thus, it can be used in sorting.

2
11/28/2012 1:59:11 PM

Popular Answer

You could try ThenByDescending:

var rows = table
    .OrderByDescending(x => x.ReadDate).Skip((pageIndex) * pageSize).Take(pageSize)
    .ThenByDescending(x => x.T1).Skip((pageIndex) * pageSize).Take(pageSize);

UPDATE: You could use Reflection (a bit slower) if ordering by one field:

var tableInfo = table.GetType().GetProperty("T1"); 
var sortedRow = table.OrderByDescending(x => tableInfo.GetValue(x, null)).Skip((pageIndex) * pageSize).Take(pageSize); 


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow