I'd like to sort DataTable by one Column of the DataTable,for example Name.While I'd like to define my own way of sorting, such as sort by the entension of the file, how to implement that way?
Asked
Active
Viewed 275 times
0
-
http://stackoverflow.com/questions/1819744/sorting-datatable-columns?rq=1 ? – iabbott Sep 13 '13 at 10:13
-
http://stackoverflow.com/questions/582374/dataview-sort-more-than-just-asc-desc-need-custom-sort – Matus Sep 13 '13 at 10:15
-
Could you please elaborate? – Sangram Nandkhile Sep 13 '13 at 10:23
3 Answers
2
The easiest and most extendable way is to use Linq-To-DataSet
and Path.GetExtension
:
var orderedRows = dataTable.AsEnumerable()
.Select(row => new { // create an anoymous type for readability
row,
extension = Path.GetExtension(row.Field<string>("Filename"))
})
.OrderBy(x => x.extension)
.Select(x => x.row);
If you need a new DataTable
from the query (you could simply loop it with foreach
) use:
dataTable = orderedRows.CopyToDataTable();

Tim Schmelter
- 450,073
- 74
- 686
- 939
1
DataTable result = dt.AsEnumerable()
.OrderBy(d=>d.Field<string>("YourFieldName"))
.CopyToDataTable();

Kaf
- 33,101
- 7
- 58
- 78
0
Easiest way: add a hidden DataColumn where you will store file extension and sort DataTable on that DataColumn as usually.

Andrius Naruševičius
- 8,348
- 7
- 49
- 78