1

I have a DataTable with column CourseNr of type String with following values:

"121"
"111"
"108"
"122"
"BH20"
"PHD45"
"ADH90"

I want to sort CourseNr column (Integers in ASC order) and (Chars in ASC alphabetically order)like this:

"108"
"111"
"121"
"122"
"ADH90"
"BH20"
"PHD45"

I know There can be many possible suggestions to solve this, But I need some best possible approach to achieve this?

SPBeginer
  • 733
  • 3
  • 14
  • 29

1 Answers1

1

You can use the windows-builtin natural-sort(like f.e. files are ordered) StrCmpLogicalW:

Compares two Unicode strings. Digits in the strings are considered as numerical content rather than text. This test is not case-sensitive.

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class NaturalStringComparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a, b);
    }
}

Then the code to sort the DataTable is easy with LINQ:

table = table.AsEnumerable()
  .OrderBy(r => r.Field<string>("CourseNr"), new NaturalStringComparer())
  .CopyToDataTable();

(credits for NaturalStringComparer to: https://stackoverflow.com/a/248613/284240)

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939