0

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?

user2677944
  • 127
  • 1
  • 5

3 Answers3

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