gpt4 book ai didi

c# - 如何对可观察集合进行排序?

转载 作者:IT王子 更新时间:2023-10-29 03:36:43 26 4
gpt4 key购买 nike

我有以下类(class):

[DataContract]
public class Pair<TKey, TValue> : INotifyPropertyChanged, IDisposable
{
public Pair(TKey key, TValue value)
{
Key = key;
Value = value;
}

#region Properties
[DataMember]
public TKey Key
{
get
{ return m_key; }
set
{
m_key = value;
OnPropertyChanged("Key");
}
}
[DataMember]
public TValue Value
{
get { return m_value; }
set
{
m_value = value;
OnPropertyChanged("Value");
}
}
#endregion

#region Fields
private TKey m_key;
private TValue m_value;
#endregion

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}

#endregion

#region IDisposable Members

public void Dispose()
{ }

#endregion
}

我将其放入 ObservableCollection 中:

ObservableCollection<Pair<ushort, string>> my_collection = 
new ObservableCollection<Pair<ushort, string>>();

my_collection.Add(new Pair(7, "aaa"));
my_collection.Add(new Pair(3, "xey"));
my_collection.Add(new Pair(6, "fty"));

问:如何按键排序?

最佳答案

这个简单的扩展对我来说效果很好。我只需要确保 MyObjectIComparable。当对 MyObjects 的可观察集合调用排序方法时,将调用 MyObject 上的 CompareTo 方法,这将调用我的逻辑排序方法。虽然它没有此处发布的其余答案的所有功能,但这正是我所需要的。

static class Extensions
{
public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable
{
List<T> sorted = collection.OrderBy(x => x).ToList();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
}

public class MyObject: IComparable
{
public int CompareTo(object o)
{
MyObject a = this;
MyObject b = (MyObject)o;
return Utils.LogicalStringCompare(a.Title, b.Title);
}

public string Title;

}
.
.
.
myCollection = new ObservableCollection<MyObject>();
//add stuff to collection
myCollection.Sort();

关于c# - 如何对可观察集合进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1945461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com