基本的に私は を持っておりKeyedCollection<string, CustomNode>
、コレクションをキーで (またはできればカスタム比較機能で) ソートできるようにしたいと考えています。
これが不可能な場合、ソート可能な値にキーが埋め込まれている別のクラスを誰かが推奨できますか?
基本的に私は を持っておりKeyedCollection<string, CustomNode>
、コレクションをキーで (またはできればカスタム比較機能で) ソートできるようにしたいと考えています。
これが不可能な場合、ソート可能な値にキーが埋め込まれている別のクラスを誰かが推奨できますか?
詳細については(上記の回答のコメントを参照)、要件は、プロパティが編集された後、要素のプロパティでソートされた「セット」を保持することです。
この場合、BindableLinq (他にも同様のフレームワークがあります) を見て、そこに実装されている OrderBy ステートメントを使用することができます。
KeyedCollection<string, CustomNode> collection = /* from whereever */
collection.Items.AsBindable().OrderBy(c => c.PropertyOnCustomNode);
編集したプロパティが PropertyChanged イベントを発生させる限り、すぐに並べ替えが適用されます。コレクションを変更する場合は、ソース コレクションが INotifyCollectionChanged を実装していることを確認してください。
同様の問題を解決しようとしているときに、この質問が来ました。それでも関連する場合は、次の例を使用して Sort を実装できました。
http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/56adc0f9-aa1b-4acf-8546-082bb01058f2/
基本的に、コレクションの基になる List をソートする必要があります。私にとって魅力のように働きました。
乾杯!
これは、ダンの回答で提供されたリンクに基づいています: http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/56adc0f9-aa1b-4acf-8546-082bb01058f2/
public class RequestTemplate : IComparable<RequestTemplate>
{
// This is the primary key for the object
private Guid _guidNumber;
// This is what a collection of these objects should be sorted by
private string _buttonCaption = "";
public Guid GuidNumber
{
get { return _guidNumber; }
set { _guidNumber = value; } // Setter only provided for deserialization usage
}
public string ButtonCaption
{
get { return _buttonCaption; }
set { _buttonCaption = value; }
}
/// <summary>
/// Method needed to allow sorting a collection of these objects.
/// </summary>
public int CompareTo(RequestTemplate other)
{
return string.Compare(this.ButtonCaption, other.ButtonCaption,
StringComparison.CurrentCultureIgnoreCase);
}
}
public class RequestTemplateKeyedCollection : KeyedCollection<Guid, RequestTemplate>
{
/// <summary>
/// Sort the collection by sorting the underlying collection, accessed by casting the Items
/// property from IList to List.
/// </summary>
public void Sort()
{
List<RequestTemplate> castList = base.Items as List<RequestTemplate>;
if (castList != null)
castList.Sort(); // Uses default Sort() for collection items (RequestTemplate)
}
/// <summary>
/// Method needed by KeyedCollection.
/// </summary>
protected override Guid GetKeyForItem(RequestTemplate requestTemplate)
{
return requestTemplate.GuidNumber;
}
}
まだ広範囲にテストしていませんが、問題なく動作するようです。
KeyCollection<T>
Collection<T>
どの実装から継承するIEnumerable
ので、使用できるはずですIEnumerable.OrderBy()
。には、カスタムの comparerIEnumerable.OrderBy()
を指定できるオーバーロードもあります。
SortedDictionaryコレクションを見るかもしれませんが、O(1) の取得を伴う KeyedCollection とは対照的に、項目の取得 O(log N) の追加費用が発生します。