Reputation: 399
How do I sort alphabetically a DataTable
, but in the same time sorting rule must take care of case, upper in front of lower, and sign does not take first place in front of latters!
Example: I want record "AXialis" in front of "All people", "FPrint" to be in front of "Finger Print", "MyRecordV2" in front of "MyRecord_v2" even if in a normal order it will be "All people", "AXialis", "Finger Print", "FPrint", "MyRecord_v2", "MyRecordV2"
Upvotes: 1
Views: 60
Reputation: 2180
By design DataViews can only be sorted using StringComparer.None
. You want to use StringComparer.Ordinal
. Which can be done using DataType::AsEnumerable() with an OrderBy() clause.
static void Main(string[] args)
{
DataTable dt = new DataTable("MainTable");
var column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "value";
// Add the Column to the DataColumnCollection.
dt.Columns.Add(column);
var stringList = new List<string> { "All people", "Finger Print", "MyRecord_v2", "MyRecordV2", "FPrint", "AXialis" };
foreach (string s in stringList)
{
var row = dt.NewRow();
row["value"] = s;
dt.Rows.Add(row);
}
Console.WriteLine("Before Sort");
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row["value"]);
}
var query = dt.AsEnumerable().OrderBy(r => r.Field<string>("value"), StringComparer.Ordinal);
Console.WriteLine("\r\nSorted");
foreach (DataRow row in query)
{
Console.WriteLine(row["value"]);
}
}
Results in:
Before Sort
All people
Finger Print
MyRecord_v2
MyRecordV2
FPrint
AXialis
Sorted
AXialis
All people
FPrint
Finger Print
MyRecordV2
MyRecord_v2
Upvotes: 4