C# SortedList 可重复键的排序键/值对集合

代码

    public class Cost

    {

        public double cost;

        public int id;

    }


    public class CostComparer : IComparer<Cost>

    {

        public int Compare(Cost x, Cost y)

        {

            if (x.cost - y.cost < 1e-10)

            {

                return -1;

            }

            else

            {

                return 1;

            }

        }

    }



错误的写法:

SortedList<double> list = new SortedList<double>(new CostComparer());\\XX

SortedList<double, Cost> list = new SortedList<double, Cost>(new CostComparer());\\XX

错误提示:

非泛型 类型“System.Collections.SortedList”不能与类型实参一起使用


可行的写法,浪费存储空间,SortedList并没有提供直接根据索引访问集合元素的方法,所以只能够通过其他的方法访问:

        SortedList<Cost, Cost> list = new SortedList<Cost, Cost>(new CostComparer());


        Cost c1 = new Cost();

        c1.cost = 20;

        c1.id = 30;

        list.Add(c1, c1);


        Cost c2 = new Cost();

        c2.cost = 10;

        c2.id = 40;

        list.Add(c2, c2);

//方法一GetEnumerator

        IEnumerator<KeyValuePair<Cost, Cost>> iter = list.GetEnumerator();

        iter.MoveNext();    

        Cost tmpKey = iter.Current.Key;

        Cost tmpValue = iter.Current.Value;

 

//方法二foreach

        foreach (KeyValuePair<Cost, Cost> t in list)

        {

            Cost tmpKey = t.Key;

            Cost tmpValue = t.Value;

        }


删除某个索引键值对:         list.RemoveAt(0);


但是为了简单起见,实际上,只是对Cost中的cost字段进行排序,并且支持重复插入,可以使用SortedSet

        SortedSet<Cost> set = new SortedSet<Cost>(new CostComparer());\\OK




    本文转自fengyuzaitu 51CTO博客,原文链接:http://blog.51cto.com/fengyuzaitu/1903015,如需转载请自行联系原作者


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值