FileListViewSorter
An IComparer for FileSystemInfos in ListViewItems.
using System.Collections;using System.IO;
using System.Windows.Forms;
namespace Library.Forms
{
/// <summary>
/// Implementation of IComparer for ListViewItems with FileSystemInfo in the Tag
/// </summary>
public class FileListViewSorter : IComparer
{
public enum SortByField
{
None,
Name,
LastWriteDate,
Extension,
FileSize
}
private SortByField _sortBy = SortByField.None;
private SortOrder _order = SortOrder.None;
private CaseInsensitiveComparer _comparer = new CaseInsensitiveComparer();
#region IComparer Members
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
/// </summary>
public int Compare(object x, object y)
{
int result;
ListViewItem lvX = (ListViewItem)x;
ListViewItem lvY = (ListViewItem)y;
FileSystemInfo fsiX = lvX.Tag as FileSystemInfo;
FileSystemInfo fsiY = lvY.Tag as FileSystemInfo;
if ((fsiX is DirectoryInfo && fsiY is DirectoryInfo)
|| (fsiX is FileInfo && fsiY is FileInfo))
{
//both the same type
result = CompareValue(fsiX, fsiY);
}
else
{
result = fsiX is DirectoryInfo ? -1 : 1;
}
if (Order == SortOrder.Descending) result = -result;
return result;
}
#endregion
private int CompareValue(FileSystemInfo x, FileSystemInfo y)
{
switch (SortBy)
{
case SortByField.None:
return 0;
case SortByField.Name:
return _comparer.Compare(x.Name, y.Name);
case SortByField.LastWriteDate:
return x.LastWriteTime.CompareTo(y.LastWriteTime);
case SortByField.Extension:
return _comparer.Compare(x.Extension, y.Extension);
case SortByField.FileSize:
if (x is DirectoryInfo) return 0;
return ((FileInfo)x).Length.CompareTo(((FileInfo)y).Length);
default:
return _comparer.Compare(x.Name, y.Name);
}
}
/// <summary>
/// Gets or sets the file attribute to sort by
/// </summary>
public SortByField SortBy
{
get { return _sortBy; }
set { _sortBy = value; }
}
/// <summary>
/// Gets or sets the column, assuming the column order (filename, extension, writedate, size)
/// </summary>
public int SortColumn
{
get
{
switch (SortBy)
{
case SortByField.Extension:
return 1;
case SortByField.LastWriteDate:
return 2;
case SortByField.FileSize:
return 3;
default:
break;
}
return 0;
}
set
{
if (value == 1)
SortBy = SortByField.Extension;
else if (value == 2)
SortBy = SortByField.LastWriteDate;
else if (value == 3)
SortBy = SortByField.FileSize;
else
SortBy = SortByField.Name;
}
}
/// <summary>
/// Gets or sets the order of sorting to apply (Ascending or Descending).
/// </summary>
public SortOrder Order
{
get { return _order; }
set { _order = value; }
}
}
}