C# 基于ObservableCollection实现集合排序
SortedObservableCollection<T, TKey>
/// <summary>
/// 使用<see cref="AddSorted"/>方法扩展<see cref="ObservableCollection{T}"/>,以将项目插入已排序的集合中。
/// </summary>
public class SortedObservableCollection<T, TKey> : ObservableCollection<T>
{
private readonly Func<T, TKey> m_KeySelector;
private readonly IComparer<TKey> m_Comparer;
/// <summary>
/// 创建一个新的SortedObservableCollection实例。
/// </summary>
/// <param name="keySelector">选择排序键的功能。</param>
public SortedObservableCollection(Func<T, TKey> keySelector)
{
this.m_KeySelector = keySelector;
this.m_Comparer = Comparer<TKey>.Default;
}
/// <summary>
/// 将项目添加到排序的集合中。
/// </summary>
/// <param name="item">项目</param>
public void AddSorted(T item)
{
int i = 0;
int maxIndex = this.Count - 1;
while (i <= maxIndex)
{
int centerIndex = (i + maxIndex) / 2;
//
// 摘要: 比较两个对象并返回指示一个是否小于、 等于还是大于另一个值。
// 参数:
// x: 要比较的第一个对象。
// y: 要比较的第二个对象。
// 返回结果:
// 小于零 : x 小于 y。
// 零 : x 等于 y。
// 大于零 : x 大于 y。
int c = m_Comparer.Compare(m_KeySelector(item), m_KeySelector(this[centerIndex]));
if (c == 0)
{
i = centerIndex;
break;
}
if (c > 0)
{
i = centerIndex + 1;
}
else
{
maxIndex = centerIndex - 1;
}
}
this.Insert(i, item);
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <param name="item"></param>
public void SetItemEx(int index, T item)
{
base.SetItem(index, item);
}
}