コード例 #1
0
 public static void AssignTo(ListView listView, params ColumnFormat[] formats)
 {
     var comparer = new ListViewItemTextComparer(listView);
     comparer.AddColumnFormats(formats);
 }
コード例 #2
0
        public int Compare(object x, object y)
        {
            var itemX = x as ListViewItem;
            var itemY = y as ListViewItem;

            if (itemX == null || itemY == null) return -1;

            if (_sortColumn >= itemX.SubItems.Count) return -1;
            if (_sortColumn >= itemY.SubItems.Count) return -1;

            var xValue = itemX.SubItems[_sortColumn].Text;
            var yValue = itemY.SubItems[_sortColumn].Text;
            var compareValue = 0;
            var columnFormat = ColumnFormat.Text;

            if (_sortColumn < _columnFormats.Count)
            {
                try { columnFormat = (ColumnFormat)_columnFormats[_sortColumn]; }
                // ReSharper disable EmptyGeneralCatchClause
                catch { }
                // ReSharper restore EmptyGeneralCatchClause
            }

            // Special case, if the column format isn't tag and any string is empty, it shouldn't be parsed
            if (columnFormat != ColumnFormat.Tag)
            {
                if (xValue == "" && yValue == "") return 0;
                if (xValue == "") return SortDescending ? 1 : -1;
                if (yValue == "") return SortDescending ? -1 : 1;
            }

            // If the column format is percentage, strip any whitespace and '%' from the value and
            // change the column format to numeric
            if (columnFormat == ColumnFormat.Percentage)
            {
                xValue = xValue.Replace("%", "").Trim();
                yValue = yValue.Replace("%", "").Trim();
                columnFormat = ColumnFormat.Numeric;
            }

            if (columnFormat == ColumnFormat.NumericUnit)
            {
                xValue = DECIMAL_REGEX.Replace(xValue, "");
                yValue = DECIMAL_REGEX.Replace(yValue, "");
                columnFormat = ColumnFormat.Numeric;
            }

            try
            {
                compareValue = CompareValues(columnFormat, xValue, yValue, itemX, itemY);
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch { }
            // ReSharper restore EmptyGeneralCatchClause

            if (compareValue == 0 && _secondSortColumn != -1 && _secondSortColumn != _sortColumn)
            {
                var comparer = new ListViewItemTextComparer
                    {
                        _columnFormats = _columnFormats,
                        SortColumn = _secondSortColumn
                    };
                compareValue = comparer.Compare(x, y);
            }

            return compareValue != 0 ? (SortDescending ? -compareValue : compareValue) : 1;
        }