Select top N rows AFTER sorting from Dataview in c#

╄→尐↘猪︶ㄣ 提交于 2019-12-12 10:57:35

问题


I have a DataTable with 10 rows say one of the columns numbered 1 to 10 randomly. I want to sort them. usually, I do this:

DataView Dv = new DataView(dtPost, "", "views desc", DataViewRowState.Unchanged);
repeater.DataSource = Dv;
repeater.DataBind();

Now, I just want to bind the top 5 rows in this Dataview. If I try this:

DvPopBlogs.Table.Rows.Cast<System.Data.DataRow>().Take(5);

OR

DvPopBlogs.Table.AsEnumerable().Take(5); //this usually works if sorting wasnt necessary

It works, but the dataView completely forgets about the sorting and just selects 5 rows from top.

I have tried it with all DataViewRowStates too. How to select top 5 rows after sorting?

I seem to run out of ideas! please help!


回答1:


You are accessing the DataView, but then asking for the Table it is bound to - the table itself isn't sorted, the DataView provides a sorted "view" of the table.

So try (warning drycode!)

DvPopBlogs.DataViewRows.Take(5)

To get the first 5 (in sort order) DataViewRows. If you want the DataRows:

DvPopBlogs.DataViewRows.Take(5).Select(dvr => dvr.Row)

It's quite possible the enumerator from DataView is the DataViewRows collection, so you may be able to just use DvPopBlogs.Take(5).... if you wish.




回答2:


Since you are casting already to a generic list, why not cast the dataview instead of the datatable?

IEnumerable<DataRow> sortedRows = DvPopBlogs.Cast<DataRowView>().Take(5).Select(r => r.Row);


来源:https://stackoverflow.com/questions/3830913/select-top-n-rows-after-sorting-from-dataview-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!