基本上我有一个KeyedCollection<string, CustomNode>
,我希望能够通过键(或者最好使用自定义比较器)对集合进行排序。
如果这是不可能的,有人可以推荐另一个类,其中键嵌入在我可以排序的值中吗?
基本上我有一个KeyedCollection<string, CustomNode>
,我希望能够通过键(或者最好使用自定义比较器)对集合进行排序。
如果这是不可能的,有人可以推荐另一个类,其中键嵌入在我可以排序的值中吗?
Upon further information (see comments on answer above), a requirement is to keep the "set" sorted by a element's property after the property is edited.
In this case, you might take a look at BindableLinq (there are other similar frameworks too) and use the OrderBy statement implemented in there.
KeyedCollection<string, CustomNode> collection = /* from whereever */
collection.Items.AsBindable().OrderBy(c => c.PropertyOnCustomNode);
As long as your edited property raises a PropertyChanged event then it'll apply the re-ordering immediately. If you wish to change your collection, then ensure that the source collection implements INotifyCollectionChanged.
在尝试解决类似问题时出现了这个问题。如果它仍然相关,我可以使用此处的示例实现排序:
http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/56adc0f9-aa1b-4acf-8546-082bb01058f2/
基本上涉及对集合的基础列表进行排序。对我来说就像一个魅力。
干杯!
KeyCollection<T>
继承自Collection<T>
which implementsIEnumerable
所以你应该能够使用IEnumerable.OrderBy()
. IEnumerable.OrderBy()
还具有允许您提供自定义比较器的重载。
这是基于 Dan 在回答中提供的链接: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;
}
}
尚未对其进行广泛测试,但似乎可以正常工作。
您可能会查看SortedDictionary集合......但这会增加项目检索 O(log N) 的费用,而不是使用 O(1) 检索的 KeyedCollection。