12

" " 連絡先オブジェクトBindingList<T>のリストを含む Windows フォームでを使用しています。IComparable<Contact>ここで、ユーザーがグリッドに表示されている任意の列で並べ替えできるようにしたいと考えています。

BindingList<T>並べ替えを許可するカスタム コレクションを実装する方法を示す方法が MSDN online で説明されています。しかし、Sort イベントや、カスタム コードを使用して基になるコレクションを並べ替えるために、DataGridView (または、さらに良い場合は BindingSource) でキャッチできるものはありませんか?

MSDN で説明されている方法はあまり好きではありません。もう 1 つの方法では、コレクションに LINQ クエリを簡単に適用できます。

4

6 に答える 6

28

私はググって、もう少し自分で試しました...

これまでのところ、.NETに組み込まれている方法はありません。に基づいてカスタムクラスを実装する必要がありますBindingList<T>。1つの方法は、カスタムデータバインディング、パート2(MSDN)で説明されています。最後に、ApplySortCoreプロジェクトに依存しない実装を提供するために、-methodの別の実装を作成します。

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

于 2008-11-11T16:08:27.910 に答える
22

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;
        }
    }
}

このバリアントにはもう少しコードが必要ですが、パフォーマンスが問題になる場合は、努力する価値があると思います。

于 2009-07-24T14:41:52.260 に答える
4

これは、いくつかの新しいトリックを使用した新しい実装です。

基になる型をIList<T>実装するvoid Sort(Comparison<T>)か、デリゲートを渡して並べ替え関数を呼び出す必要があります。(機能IList<T>はありませんvoid Sort(Comparison<T>))

静的コンストラクターの間、クラスは、後で使用するために作成するデリゲートを実装またはキャッシュするTすべてのパブリック インスタンス化されたプロパティを検索する型を調べます。の型ごとに 1 回だけ実行する必要があり、読み取り時にスレッド セーフであるため、これは静的コンストラクターで実行されます。ICompareableICompareable<T>TDictionary<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;
        }
    }
}
于 2013-12-05T17:08:04.737 に答える
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;
   }
  }
 }
}
于 2010-09-10T19:41:52.020 に答える
0

カスタム オブジェクト用ではありません。.Net 2.0 では、BindingList を使用して並べ替えを行う必要がありました。.Net 3.5 には何か新しいものがあるかもしれませんが、まだ調べていません。LINQ とそれに付随する並べ替えオプションがあるため、実装がより簡単になる可能性があります。

于 2008-10-30T11:06:36.313 に答える