Are you trying to use Linq2Sql? If so, you can just do:
var result = from x in MyDataTable
orderby x.Date ascending
select x;
(replace ascending
by descending
if you want it to go the other way).
If you would like to optionally sort it, you can use IQueryable<T>
s and optionally sort, a la:
IQueryable<MyDataTable> GetData(bool sortByDate)
{
var result = from x in DataContext.Table<MyDataTable>
where SomeMatchingClause(x)
select x;
if(sortByDate)
{
result = result.OrderBy(x => x.Date); // or OrderByDescending
}
return result;
}
If you're querying in SQL directly, just do
SELECT * FROM MyTable ORDER BY Date ASC
(replace ASC
with DESC
if you want it to go the other way)
I don't frequently build SQL queries as string
s in C#, but if you wanted to make this optional, I guess you could incrementally build the query, even though it's really gross:
string GetSqlQuery(bool sortByDate)
{
string result = "SELECT * FROM MyTable";
if(sortByDate)
{
result += " ORDER BY Date ASC";
}
return result;
}