温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-23 22:08:49 来源:网络 阅读:7186 作者:fengyuzaitu 栏目:编程语言

代码

    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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI