至少有一个对象必须实现IComparable?

时间:2012-11-28 12:31:18

标签: asp.net-mvc linq dynamic-linq

型号:

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>();

查询

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)

当我通过ReadDate订购时,它有效。但是当我尝试按其他字段排序时,我收到错误:At least one object must implement IComparable

为什么我收到此错误?我该如何解决?

2 个答案:

答案 0 :(得分:2)

如果要对任何类型的项目列表进行排序,则类型必须实现IComparable才能使排序算法能够比较项目。 T1IQueryable,没有实现IComparable。我认为你打算为T1,T2和T3创建字符串值。如果是这样,您应该为每个创建T1等的linq语句添加FirstOrDefault()

修改

(评论后)

我的意思是:

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

现在T1是一个字符串,因此可以用于排序。

答案 1 :(得分:0)

您可以尝试ThenByDescending

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

<强>更新: 如果按一个字段排序,你可以使用Reflection(慢一点):

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