2011-01-12 51 views
3

基本上我有KeyedCollection<string, CustomNode>,我希望能夠通過鍵(或最好使用自定義比較器)對集合進行排序。如何對KeyedCollection <TKey, TItem>進行排序?

如果這是不可能的,有人可以推薦另一個類,其中的密鑰嵌入到我可以排序的值中嗎?

+0

您聲明密鑰(字符串)可能會更改,因此它不是硬靜態密鑰。如果數據沒有經典密鑰,那麼不要使用密鑰或值集合(即使密鑰來自一個值)。我只是使用一個List並使用LINQ進行排序。如果密鑰正在更改,mycolletion [key]沒有那麼多實用性,並且如果找不到密鑰則會拋出異常。此時您正在搜索動態數據,您可以使用LINQ。 – Paparazzi 2012-03-24 18:27:35

回答

-1

爲什麼不只是使用SortedList<TKey, TValue>類?從Collection<T>

MSDN link

+2

由於KeyedCollection推斷鍵值,而不是強制您顯式添加鍵值。 – 2011-01-12 00:33:14

+2

這個。我說我想要鑰匙被嵌入。 – Miguel 2011-01-12 00:34:07

2

KeyCollection<T>繼承它實現IEnumerable所以你應該能夠使用IEnumerable.OrderBy()IEnumerable.OrderBy()也有一個超載,allows you to supply a custom comparer

+4

OrderBy雖然返回一個新的集合,但它不排序當前的集合。 – Miguel 2011-01-12 06:21:42

-1

你可能會看看SortedDictionary集合...但是這會帶來項目檢索O(log N)的附加費用,而不是帶有O(1)檢索的KeyedCollection。

+2

另一個類*其中的密鑰嵌入值* – Miguel 2011-01-12 00:34:42

2

有關更多信息(請參閱上面關於answer的評論),要求在編輯屬性之後讓「set」按元素的屬性排序。

在這種情況下,您可以看看BindableLinq(還有其他類似的框架),並使用其中實現的OrderBy語句。

KeyedCollection<string, CustomNode> collection = /* from whereever */ 
collection.Items.AsBindable().OrderBy(c => c.PropertyOnCustomNode); 

只要您編輯的屬性引發一個PropertyChanged事件,那麼它將立即應用重新排序。如果您想更改集合,請確保源集合實現INotifyCollectionChanged。

1

這是基於由丹在回答中提供的鏈接: 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; 
     } 
    } 

沒有測試它仍然廣泛,但它似乎工作確定。

相關問題