2018-07-15 18:12:02 +00:00
|
|
|
using System;
|
|
|
|
using System.Collections;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.ComponentModel;
|
2020-10-18 18:02:39 +00:00
|
|
|
using System.Globalization;
|
2018-07-15 18:12:02 +00:00
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
namespace PKHeX.WinForms
|
|
|
|
{
|
2020-10-18 18:02:39 +00:00
|
|
|
public sealed class PropertyComparer<T> : IComparer<T> where T : class
|
2018-07-15 18:12:02 +00:00
|
|
|
{
|
|
|
|
private readonly IComparer comparer;
|
|
|
|
private PropertyDescriptor propertyDescriptor;
|
|
|
|
private int reverse;
|
|
|
|
|
|
|
|
public PropertyComparer(PropertyDescriptor property, ListSortDirection direction)
|
|
|
|
{
|
|
|
|
propertyDescriptor = property;
|
|
|
|
Type comparerForPropertyType = typeof(Comparer<>).MakeGenericType(property.PropertyType);
|
2020-10-18 18:02:39 +00:00
|
|
|
var ci = comparerForPropertyType.InvokeMember("Default", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.Public, null, null, null);
|
|
|
|
comparer = ci == null ? new Comparer(CultureInfo.InvariantCulture) : (IComparer) ci;
|
2018-07-15 18:12:02 +00:00
|
|
|
SetListSortDirection(direction);
|
|
|
|
}
|
|
|
|
|
|
|
|
#region IComparer<T> Members
|
|
|
|
|
2020-10-18 18:02:39 +00:00
|
|
|
public int Compare(T? x, T? y)
|
2018-07-15 18:12:02 +00:00
|
|
|
{
|
2020-10-18 18:02:39 +00:00
|
|
|
if (x == null) throw new ArgumentNullException(nameof(x));
|
|
|
|
if (y == null) throw new ArgumentNullException(nameof(y));
|
2018-07-15 18:12:02 +00:00
|
|
|
return reverse * comparer.Compare(propertyDescriptor.GetValue(x), propertyDescriptor.GetValue(y));
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
private void SetPropertyDescriptor(PropertyDescriptor descriptor)
|
|
|
|
{
|
|
|
|
propertyDescriptor = descriptor;
|
|
|
|
}
|
|
|
|
|
|
|
|
private void SetListSortDirection(ListSortDirection direction)
|
|
|
|
{
|
|
|
|
reverse = direction == ListSortDirection.Ascending ? 1 : -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void SetPropertyAndDirection(PropertyDescriptor descriptor, ListSortDirection direction)
|
|
|
|
{
|
|
|
|
SetPropertyDescriptor(descriptor);
|
|
|
|
SetListSortDirection(direction);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|