I thought about this a long time ago, and the solution I came up with is amazingly obvious: in essence, ordering is all about comparison - so why don't we just write a custom Comparer ...
public class MyComparer : IComparer<string> { private readonly string _columnName; public MyComparer(string columnName) { _columnName = columnName; } public int Compare(string leftValue, string rightValue) { double leftDouble, rightDouble; switch (_columnName) { case "Account": if (Double.TryParse(leftValue, out leftDouble) && Double.TryParse(rightValue, out rightDouble)) { return leftDouble.CompareTo(rightDouble); } else { return String.Compare(leftValue, rightValue); } default: return String.Compare(leftValue, rightValue); } } }
... and just add it to OrderBy ...
public DataTable sortData(string columnName) { DataTable dt1=new DataTable(); return dt1=dataMgr[DatabaseFileNames.ControlDatabase]["OrderedTableName"] .Select("Department='CSC'") .OrderBy(x => x.Field<string>(columnName) ?? String.Empty, new MyComparer(columnName) ) .CopyToDataTable(); }
... and we are done and we can even extend this solution to use other data types, for example. DateTime
source share