1

I have a datatable with several columns of strings. One column is "IPAddress". I want to sort the data table by the IP Address column. I've tried

DataView dv = dt.DefaultView;
dv.Sort = "IPAddress asc";
dt = dv.ToTable();

But of course this produces a result where, for example 10.1.1.203 comes before 10.1.1.21 instead of after.

There was a really clever solution here How to sort list of Ip Addresses using c# but this works for lists, not datatables.

Edit: This is not a duplicate question, as the linked question is almost 10 years old and a lot has changed since then, and more importantly, the question does not specifically address the problem of IP address sorting which is very specific and unique problem.

Mark Masic
  • 83
  • 1
  • 11
  • Custom sorting not supported to my knowledge - linked (as [duplicate](https://stackoverflow.com/questions/582374/dataview-sort-more-than-just-asc-desc-need-custom-sort)) question shows possible solutions including adding extra column strictly for sorting. – Alexei Levenkov Dec 19 '18 at 04:00
  • I would take advantage of the fact that an IP address is a set of exactly 4 dot-separated numeric values, just like a [Version](https://learn.microsoft.com/en-us/dotnet/api/system.version?view=netframework-4.7.2). The `Version` type handles sorting correctly, so if you put your IP address value into Version objects, they will probably sort correctly. – Richardissimo Dec 19 '18 at 06:37
  • Depending on your DB you may have a specific `inet` type that records these things properly (they are not strings, but 4 integers or 1 integer depending on how you view it, which could be the basis of a solution, just convert it to an integer before sorting: `256^3*item1+256^2*item2+256*item3+item4`). Do not forget about IPv6 too! – Patrick Mevzek Dec 19 '18 at 16:32
  • @Richardissimo: could you please provide an example. `dt.Columns.Add("IP", System.Type.GetType("System.Version"))` doesn't work. @Mark Masic: did you figure this out? =) – Alex G Jan 20 '21 at 06:15
  • 1
    @AlexG That probably didn't work because the type of that column *was not* a Version (you can't just say "this is a Version" when it isn't). You could add another column to your DataTable of type Version, and populate the value in each row from the current column, converted to a Version (e.g. use the constructor which takes a string parameter). – Richardissimo Jan 20 '21 at 09:34
  • @Richardissimo. Thanks, I got it to work! `dt.Columns.Add("IP", typeof(Version));` and `dt.Rows.Add(Version.Parse(ip.ToString()));` – Alex G Jan 20 '21 at 14:16

0 Answers0