溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C# SortedList 可重復(fù)鍵的排序鍵/值對(duì)集合

發(fā)布時(shí)間:2020-06-23 22:08:49 來源:網(wǎng)絡(luò) 閱讀:7193 作者: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;

            }

        }

    }



錯(cuò)誤的寫法:

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

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

錯(cuò)誤提示:

非泛型 類型“System.Collections.SortedList”不能與類型實(shí)參一起使用


可行的寫法,浪費(fèi)存儲(chǔ)空間,SortedList并沒有提供直接根據(jù)索引訪問集合元素的方法,所以只能夠通過其他的方法訪問:

        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;

        }


刪除某個(gè)索引鍵值對(duì):         list.RemoveAt(0);


但是為了簡單起見,實(shí)際上,只是對(duì)Cost中的cost字段進(jìn)行排序,并且支持重復(fù)插入,可以使用SortedSet

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


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI