ListViewColumnSorter.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. namespace LYFZ.ComponentLibrary
  8. {
  9. public class ListViewColumnSorter : IComparer
  10. {
  11. /// <summary>
  12. /// 指定按照哪个列排序
  13. /// </summary>
  14. private int ColumnToSort;
  15. /// <summary>
  16. /// 指定排序的方式
  17. /// </summary>
  18. private SortOrder OrderOfSort;
  19. /// <summary>
  20. /// 声明CaseInsensitiveComparer类对象,
  21. /// 参见ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfSystemCollectionsCaseInsensitiveComparerClassTopic.htm
  22. /// </summary>
  23. private CaseInsensitiveComparer ObjectCompare;
  24. /// <summary>
  25. /// 构造函数
  26. /// </summary>
  27. public ListViewColumnSorter()
  28. {
  29. // 默认按第一列排序
  30. ColumnToSort = 0;
  31. // 排序方式为不排序
  32. OrderOfSort = SortOrder.None;
  33. // 初始化CaseInsensitiveComparer类对象
  34. ObjectCompare = new CaseInsensitiveComparer();
  35. }
  36. /// <summary>
  37. /// 重写IComparer接口.
  38. /// </summary>
  39. /// <param name="x">要比较的第一个对象</param>
  40. /// <param name="y">要比较的第二个对象</param>
  41. /// <returns>比较的结果.如果相等返回0,如果x大于y返回1,如果x小于y返回-1</returns>
  42. public int Compare(object x, object y)
  43. {
  44. int compareResult;
  45. ListViewItem listviewX, listviewY;
  46. // 将比较对象转换为ListViewItem对象
  47. listviewX = (ListViewItem)x;
  48. listviewY = (ListViewItem)y;
  49. // 比较
  50. if (LYFZ.Command.Command_Validate.IsNumeric(listviewX.SubItems[ColumnToSort].Text.Trim()) && LYFZ.Command.Command_Validate.IsNumeric(listviewY.SubItems[ColumnToSort].Text.Trim()))
  51. { compareResult = ObjectCompare.Compare(Convert.ToDecimal(listviewX.SubItems[ColumnToSort].Text.Trim()), Convert.ToDecimal(listviewY.SubItems[ColumnToSort].Text.Trim())); }
  52. else
  53. { compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text.Trim(), listviewY.SubItems[ColumnToSort].Text.Trim()); }
  54. // 根据上面的比较结果返回正确的比较结果
  55. if (OrderOfSort == SortOrder.Ascending)
  56. {
  57. // 因为是正序排序,所以直接返回结果
  58. return compareResult;
  59. }
  60. else if (OrderOfSort == SortOrder.Descending)
  61. {
  62. // 如果是反序排序,所以要取负值再返回
  63. return (-compareResult);
  64. }
  65. else
  66. {
  67. // 如果相等返回0
  68. return 0;
  69. }
  70. }
  71. /// <summary>
  72. /// 获取或设置按照哪一列排序.
  73. /// </summary>
  74. public int SortColumn
  75. {
  76. set
  77. { ColumnToSort = value; }
  78. get
  79. { return ColumnToSort; }
  80. }
  81. /// <summary>
  82. /// 获取或设置排序方式.
  83. /// </summary>
  84. public SortOrder Order
  85. {
  86. set
  87. { OrderOfSort = value; }
  88. get
  89. { return OrderOfSort; }
  90. }
  91. }
  92. }