Подтвердить что ты не робот

Сортировка DataGridView и, например, BindingList <T> в .NET.

Я использую BindingList<T> в своих Windows Forms, который содержит список контактных объектов IComparable<Contact>. Теперь я хочу, чтобы пользователь мог сортировать по любому столбцу, отображаемому в сетке.

Существует способ, описанный в MSDN в Интернете, который показывает, как реализовать пользовательскую коллекцию на основе BindingList<T>, которая позволяет сортировать. Но не существует ли Сорт-событие или что-то, что можно было бы поймать в DataGridView (или, что еще лучше, на BindingSource), чтобы отсортировать базовую коллекцию с помощью пользовательского кода?

Мне не очень нравится способ, описанный MSDN. Другим способом я мог легко применить запрос LINQ к коллекции.

4b9b3361

Ответ 1

Я высоко ценю решение Matthias за его простоту и красоту.

Однако, хотя это дает отличные результаты для небольших объемов данных, при работе с большими объемами данных производительность не так хороша из-за отражения.

Я проверил тест с набором простых объектов данных, считая 100000 элементов. Сортировка по типу целочисленного типа заняла около 1 мин. Реализация, которую я собираюсь подробно описать, изменила это на ~ 200 мс.

Основная идея заключается в том, чтобы использовать строго типизированное сравнение, сохраняя при этом метод ApplySortCore. Ниже заменяется общий делегат сравнения с вызовом конкретного компаратора, реализованный в производном классе:

Новое в SortableBindingList <T> :

protected abstract Comparison<T> GetComparer(PropertyDescriptor prop);

ApplySortCore изменяет на:

protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
    List<T> itemsList = (List<T>)this.Items;
    if (prop.PropertyType.GetInterface("IComparable") != null)
    {
        Comparison<T> comparer = GetComparer(prop);
        itemsList.Sort(comparer);
        if (direction == ListSortDirection.Descending)
        {
            itemsList.Reverse();
        }
    }

    isSortedValue = true;
    sortPropertyValue = prop;
    sortDirectionValue = direction;
}

Теперь в производном классе необходимо реализовать сопоставления для каждого свойства сортировки:

class MyBindingList:SortableBindingList<DataObject>
{
        protected override Comparison<DataObject> GetComparer(PropertyDescriptor prop)
        {
            Comparison<DataObject> comparer;
            switch (prop.Name)
            {
                case "MyIntProperty":
                    comparer = new Comparison<DataObject>(delegate(DataObject x, DataObject y)
                        {
                            if (x != null)
                                if (y != null)
                                    return (x.MyIntProperty.CompareTo(y.MyIntProperty));
                                else
                                    return 1;
                            else if (y != null)
                                return -1;
                            else
                                return 0;
                        });
                    break;

                    // Implement comparers for other sortable properties here.
            }
            return comparer;
        }
    }
}

Этот вариант требует немного больше кода, но, если производительность является проблемой, я думаю, что это стоит усилий.

Ответ 2

Я googled и попробовал самостоятельно еще немного времени...

В .NET пока нет встроенного способа. Вы должны реализовать пользовательский класс на основе BindingList<T>. Один из способов описан в Custom Data Binding, часть 2 (MSDN). Наконец, я создаю другую реализацию метода ApplySortCore, чтобы обеспечить реализацию, которая не зависит от проекта.

protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
{
    List<T> itemsList = (List<T>)this.Items;
    if(property.PropertyType.GetInterface("IComparable") != null)
    {
        itemsList.Sort(new Comparison<T>(delegate(T x, T y)
        {
            // Compare x to y if x is not null. If x is, but y isn't, we compare y
            // to x and reverse the result. If both are null, they're equal.
            if(property.GetValue(x) != null)
                return ((IComparable)property.GetValue(x)).CompareTo(property.GetValue(y)) * (direction == ListSortDirection.Descending ? -1 : 1);
            else if(property.GetValue(y) != null)
                return ((IComparable)property.GetValue(y)).CompareTo(property.GetValue(x)) * (direction == ListSortDirection.Descending ? 1 : -1);
            else
                return 0;
        }));
    }

    isSorted = true;
    sortProperty = property;
    sortDirection = direction;
}

Используя этот, вы можете сортировать любой член, который реализует IComparable.

Ответ 3

Я понимаю, что все эти ответы были хорошими в то время, когда они были написаны. Наверное, они все еще есть. Я искал что-то подобное и нашел альтернативное решение для преобразования любого списка или коллекции в сортируемый BindingList<T>.

Вот важный фрагмент (ссылка на полный образец приведена ниже):

void Main()
{
    DataGridView dgv = new DataGridView();
    dgv.DataSource = new ObservableCollection<Person>(Person.GetAll()).ToBindingList();
}    

В этом решении используется метод расширения, доступный в библиотеке Entity Framework. Поэтому перед тем, как продолжить, рассмотрите следующее:

  • Если вы не хотите использовать Entity Framework, это прекрасно, это решение тоже не использует. Мы просто используем метод расширения, который они разработали. Размер EntityFramework.dll составляет 5 МБ. Если он слишком велик для вас в эпоху Petabytes, не стесняйтесь извлекать метод и его зависимости из приведенной выше ссылки.
  • Если вы используете (или хотите использовать) Entity Framework ( >= v6.0), вам не о чем беспокоиться. Просто установите пакет Entity Framework Nuget и начните работу.

Я загрузил LINQPad пример кода здесь.

  • Загрузите образец, откройте его с помощью LINQPad и нажмите F4.
  • Вы должны увидеть EntityFramework.dll красным цветом. Загрузите dll из этого location. Просмотрите и добавьте ссылку.
  • Нажмите "ОК". Хит F5.

Как вы можете видеть, вы можете сортировать по всем четырем столбцам разных типов данных, щелкнув заголовки столбцов в элементе управления DataGridView.

Те, у кого нет LINQPad, все равно могут загрузить запрос и открыть его с помощью блокнота, чтобы увидеть полный образец.

Ответ 4

Вот альтернатива, которая очень чиста и прекрасно работает в моем случае. У меня уже были специальные функции сравнения, настроенные для использования с List.Sort(Comparison), поэтому я просто адаптировал это из частей других примеров StackOverflow.

class SortableBindingList<T> : BindingList<T>
{
 public SortableBindingList(IList<T> list) : base(list) { }

 public void Sort() { sort(null, null); }
 public void Sort(IComparer<T> p_Comparer) { sort(p_Comparer, null); }
 public void Sort(Comparison<T> p_Comparison) { sort(null, p_Comparison); }

 private void sort(IComparer<T> p_Comparer, Comparison<T> p_Comparison)
 {
  if(typeof(T).GetInterface(typeof(IComparable).Name) != null)
  {
   bool originalValue = this.RaiseListChangedEvents;
   this.RaiseListChangedEvents = false;
   try
   {
    List<T> items = (List<T>)this.Items;
    if(p_Comparison != null) items.Sort(p_Comparison);
    else items.Sort(p_Comparer);
   }
   finally
   {
    this.RaiseListChangedEvents = originalValue;
   }
  }
 }
}

Ответ 5

Вот новое внедрение с использованием нескольких новых трюков.

Основной тип IList<T> должен реализовать void Sort(Comparison<T>) или вы должны передать делегату вызов функции сортировки для вас. (IList<T> не имеет функции void Sort(Comparison<T>))

Во время статического конструктора класс будет проходить через тип T, находящий все общедоступные свойства, реализующие ICompareable или ICompareable<T>, и кэширует создаваемые им делегаты для последующего использования. Это делается в статическом конструкторе, потому что нам нужно сделать это только один раз за тип T и Dictionary<TKey,TValue> - это потокобезопасный при чтении.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace ExampleCode
{
    public class SortableBindingList<T> : BindingList<T>
    {
        private static readonly Dictionary<string, Comparison<T>> PropertyLookup;
        private readonly Action<IList<T>, Comparison<T>> _sortDelegate;

        private bool _isSorted;
        private ListSortDirection _sortDirection;
        private PropertyDescriptor _sortProperty;

        //A Dictionary<TKey, TValue> is thread safe on reads so we only need to make the dictionary once per type.
        static SortableBindingList()
        {
            PropertyLookup = new Dictionary<string, Comparison<T>>();
            foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                Type propertyType = property.PropertyType;
                bool usingNonGenericInterface = false;

                //First check to see if it implments the generic interface.
                Type compareableInterface = propertyType.GetInterfaces()
                    .FirstOrDefault(a => a.Name == "IComparable`1" &&
                                         a.GenericTypeArguments[0] == propertyType);

                //If we did not find a generic interface then use the non-generic interface.
                if (compareableInterface == null)
                {
                    compareableInterface = propertyType.GetInterface("IComparable");
                    usingNonGenericInterface = true;
                }

                if (compareableInterface != null)
                {
                    ParameterExpression x = Expression.Parameter(typeof(T), "x");
                    ParameterExpression y = Expression.Parameter(typeof(T), "y");

                    MemberExpression xProp = Expression.Property(x, property.Name);
                    Expression yProp = Expression.Property(y, property.Name);

                    MethodInfo compareToMethodInfo = compareableInterface.GetMethod("CompareTo");

                    //If we are not using the generic version of the interface we need to 
                    // cast to object or we will fail when using structs.
                    if (usingNonGenericInterface)
                    {
                        yProp = Expression.TypeAs(yProp, typeof(object));
                    }

                    MethodCallExpression call = Expression.Call(xProp, compareToMethodInfo, yProp);

                    Expression<Comparison<T>> lambada = Expression.Lambda<Comparison<T>>(call, x, y);
                    PropertyLookup.Add(property.Name, lambada.Compile());
                }
            }
        }

        public SortableBindingList() : base(new List<T>())
        {
            _sortDelegate = (list, comparison) => ((List<T>)list).Sort(comparison);
        }

        public SortableBindingList(IList<T> list) : base(list)
        {
            MethodInfo sortMethod = list.GetType().GetMethod("Sort", new[] {typeof(Comparison<T>)});
            if (sortMethod == null || sortMethod.ReturnType != typeof(void))
            {
                throw new ArgumentException(
                    "The passed in IList<T> must support a \"void Sort(Comparision<T>)\" call or you must provide one using the other constructor.",
                    "list");
            }

            _sortDelegate = CreateSortDelegate(list, sortMethod);
        }

        public SortableBindingList(IList<T> list, Action<IList<T>, Comparison<T>> sortDelegate)
            : base(list)
        {
            _sortDelegate = sortDelegate;
        }

        protected override bool IsSortedCore
        {
            get { return _isSorted; }
        }

        protected override ListSortDirection SortDirectionCore
        {
            get { return _sortDirection; }
        }

        protected override PropertyDescriptor SortPropertyCore
        {
            get { return _sortProperty; }
        }

        protected override bool SupportsSortingCore
        {
            get { return true; }
        }

        private static Action<IList<T>, Comparison<T>> CreateSortDelegate(IList<T> list, MethodInfo sortMethod)
        {
            ParameterExpression sourceList = Expression.Parameter(typeof(IList<T>));
            ParameterExpression comparer = Expression.Parameter(typeof(Comparison<T>));
            UnaryExpression castList = Expression.TypeAs(sourceList, list.GetType());
            MethodCallExpression call = Expression.Call(castList, sortMethod, comparer);
            Expression<Action<IList<T>, Comparison<T>>> lambada =
                Expression.Lambda<Action<IList<T>, Comparison<T>>>(call,
                    sourceList, comparer);
            Action<IList<T>, Comparison<T>> sortDelegate = lambada.Compile();
            return sortDelegate;
        }

        protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
        {
            Comparison<T> comparison;

            if (PropertyLookup.TryGetValue(property.Name, out comparison))
            {
                if (direction == ListSortDirection.Descending)
                {
                    _sortDelegate(Items, (x, y) => comparison(y, x));
                }
                else
                {
                    _sortDelegate(Items, comparison);
                }

                _isSorted = true;
                _sortProperty = property;
                _sortDirection = direction;

                OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, property));
            }
        }

        protected override void RemoveSortCore()
        {
            _isSorted = false;
        }
    }
}

Ответ 6

Не для пользовательских объектов. В .Net 2.0 мне пришлось сортировать сортировку с помощью BindingList. В .Net 3.5 может быть что-то новое, но я еще не изучил это. Теперь, когда есть LINQ и параметры сортировки, которые возникают, если теперь это может быть проще реализовать.