code_junkie

How to Naturally Sort a DataView with something like IComparable

Nov 10th, 2011
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. DataView dataView = (DataView)Session["kingdomData"];
  2. dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
  3. gvAllData.DataSource = dataView;
  4. gvAllData.DataBind();
  5.  
  6.  
  7.  
  8. private string ConvertSortDirectionToSql(SortDirection sortDirection)
  9. {
  10. string newSortDirection = String.Empty;
  11. if (Session["SortDirection"] == null)
  12. {
  13. switch (sortDirection)
  14. {
  15. case SortDirection.Ascending:
  16. newSortDirection = "ASC";
  17. break;
  18. case SortDirection.Descending:
  19. newSortDirection = "DESC";
  20. break;
  21. }
  22. }
  23. else
  24. {
  25. newSortDirection = Session["SortDirection"].ToString();
  26. switch (newSortDirection)
  27. {
  28. case "ASC":
  29. newSortDirection = "DESC";
  30. break;
  31. case "DESC":
  32. newSortDirection = "ASC";
  33. break;
  34. }
  35. }
  36. Session["SortDirection"] = newSortDirection;
  37. return newSortDirection;
  38. }
  39.  
  40. DataView dv = new DataView(dt);
  41. ArrayList lst = new ArrayList();
  42. lst.AddRange(dv.Table.Rows);
  43. lst.Sort(new MyComparer());
  44. foreach (DataRow dr in lst)
  45. Debug.WriteLine(dr[0]);
  46.  
  47. class MyComparer : IComparer
  48. {
  49. public int Compare(object x, object y)
  50. {
  51. DataRow rx = x as DataRow;
  52. DataRow ry = y as DataRow;
  53. string datax = (string)rx[colName];
  54. string datay = (string)ry[colName];
  55. // Process datax and datay here then compare them (ASC)
  56. return datax.CompareTo(datay);
  57. }
  58. }
  59.  
  60. int cmp = colAx.CompareTo(colAy);
  61. if (cmp != 0)
  62. return cmp;
  63. cmp = colBy.CompareTo(colBx);
  64. return cmp;
  65.  
  66. dataview.sort = e.sortexpression + " " + e.Sortdirection;
  67.  
  68. DataView dv = GetDataViewSomewhere();
  69.  
  70. //Naturally sort by COLUMN_TO_SORT_ON
  71. try
  72. {
  73. List<string> rowList = new List<string>();
  74. foreach (DataRowView drv in dv)
  75. rowList.Add((string)drv["COLUMN_TO_SORT_ON"]);
  76. rowList.Sort(new NaturalComparer());
  77. Dictionary<string, int> sortValueHash = new Dictionary<string, int>();
  78. for (int i = 0; i < rowList.Count; i++)
  79. sortValueHash.Add(rowList[i], i);
  80.  
  81. dv.Table.Columns.Add("NATURAL_SORT_ORDER", typeof(int));
  82. foreach (DataRowView drv in dv)
  83. drv["NATURAL_SORT_ORDER"] = sortValueHash[(string)drv["COLUMN_TO_SORT_ON"]];
  84. dv.Sort = "NATURAL_SORT_ORDER";
  85. }
  86. catch (Exception)
  87. {
  88. DEBUG_TRACE("Could not naturally sort");
  89. dv.Sort = "COLUMN_TO_SORT_ON";
  90. }
Add Comment
Please, Sign In to add comment