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)

It works when I order by ReadDate. But when I attempt to arrange by other fields, I get the following error:At least one object must implement IComparable

Why do I get this error? How can I make it right?

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

Accepted Answer

Any kind of item must support sorting if you wish to sort a list of those objects.IComparable for items to be compared by the sort algorithm.T1 is anIQueryable which doesn't really implementIComparable . For T1, T2, and T3, I believe you wanted to generate string values. If so, you need to includeFirstOrDefault() every linq statement that creates T1, etc.

Edit

(Following your remark)

I'm saying this:

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

Now T1 is a string, making it suitable for sorting.

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

Popular Answer

You might attemptThenByDescending :

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

If ordering by a single field, you might utilize reflection (a little bit more slowly): UPDATE

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