sam yi
sam yi

Reputation: 4934

DataTable SortBy (Custom?)

Please bear with me... I'm a database professional and this is what I normally do in the database when you need some quick custom sorting...

select *
from <table>
where columnname = 'something'
order by case column2 when 'c' then 1 when 'z' then 2 end

I'm trying to replicate that in C# using DataTables. Short of creating comparison functions outlined here.. Is there a simpler/quicker/dirtier way to do this...

This is what I originally tried to do...

foreach(DataRow row in dt.Select("column1 = false","Column2 ASC, case Column3 when 'something' then 1 when 'somethingelse' then 2 else 3 end"))

Upvotes: 1

Views: 221

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use Linq-To-DataSet to achieve the same:

var ordered = from row in dt.AsEnumerable()
              let col2 = row.Field<string>("column2")
              orderby  col2 == "something" ? 1 : col2 == "somethingElse" ? 2 : 3
              select row;

You can remember how it works in this way: the comparison returns a bool where true is 1 and false is 0. If you want it to be at the end you either have to reverse the condition or (better) use ascending instead. (related to the first version)

Now you can loop it with a foreach:

foreach(DataRow row in ordered)
{
    // ..
}

or create a collection with ToList/ToArray or more appropriate a DataTable:

DataTable orderedTable = ordered.CopyToDataTale();

Upvotes: 3

Related Questions