【问题标题】:How to sort dataset.table[0] then get the top 10?如何对 dataset.table[0] 进行排序然后获得前 10 名?
【发布时间】:2009-09-13 12:15:19
【问题描述】:

我正在向我的表中添加一个自动递增列(称为“rowNum”),它运行良好,之后我使用此代码对数据表行进行排序:

DataView dv = MyDataSet.Tables[0].DefaultView;
dv.Sort = "columnName DESC";

其中 columnName 是我的列之一(不是自动增量列)。

现在,问题是: 当我想获得前 10 行时,我使用此代码:

dv.RowFilter = "rowNum <= 10";

结果不是我想要的,因为当我执行dv.Sort 时,rowNum 被打乱了(顺序错误)。

排序后如何获得前 10 行?

【问题讨论】:

    标签: c# visual-studio datatable sorting dataview


    【解决方案1】:

    我更喜欢 LINQ 来处理这样的事情。相反,我使用 System.Linq 并写:

    var rows = MyDataSet.Tables[0].AsEnumerable()
       .OrderByDescending(r => r["columnName"]) 
       .Take(10);
    

    然后绑定到“行”。

    【讨论】:

    • 非常感谢您的帮助,但您认为这种方式对超过 1000 行是否有用?。
    • 是的。它至少应该和 DataView 解决方案一样好用。
    【解决方案2】:

    如果在 AsEnumerable() 行中添加 .Take(10) 不起作用。但是如果添加下面提到的第二行是有效的。

    var Rows = (from row in dt.AsEnumerable() 
    orderby row["CostPerVeteran"] descending
    select row);
    
    dtChart = Rows.Take(10).CopyToDataTable();

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多