C# 基于ObservableCollection<T>实现集合排序

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);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Daniel大妞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值