3

模型:

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

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

4

2 回答 2

2

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

编辑

(在您发表评论后)

我的意思是:

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

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

于 2012-11-28T13:24:30.507 回答
0

你可以试试ThenByDescending

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

更新:如果按一个字段排序,您可以使用反射(慢一点):

var tableInfo = table.GetType().GetProperty("T1"); 
var sortedRow = table.OrderByDescending(x => tableInfo.GetValue(x, null)).Skip((pageIndex) * pageSize).Take(pageSize); 
于 2012-11-28T13:43:33.313 回答