首页 > 解决方案 > c# Sorted List 按 Key Groups 获取元素

问题描述

我有一个实现排序列表的类:

public class Plates : IEnumerable<KeyValuePair<string, Plate>> {

    private SortedList<string, Plate> sortedPlates;

    public Plates() {
        sortedPlates = new SortedList<string, Plate>(new KeyComparer());
       
    }

   ...some additiona data such getters and setters

}

KeyComparer 看起来像这样:

 //Left part of comparer is bigger result is 1, right -1 , equal 0
    class KeyComparer : IComparer<string> {
        public int Compare(string x, string y) {

            //Split string into numbers
            var xs = x.Split(';');
            var ys = y.Split(';');

            //Take the smallest array
            int min = Math.Min(xs.Length, ys.Length);

            //Iterate the smallest amount of elements
            for (int i = 0; i < min; i++) {

                //Cast to integers
                int a = Convert.ToInt32(xs[i]);
                int b = Convert.ToInt32(ys[i]);

                //Compare
                //int cmp = xs[i].CompareTo(ys[i]);
                int cmp = a.CompareTo(b);

                //If values are not the same return
                if (cmp != 0)
                    return cmp;
            }

            //Elsewise give priority to the smallest one
            return xs.Length.CompareTo(ys.Length);
        }

排序列表的键如下所示(不带括号)。索引用于跟踪对象组。

[0;0]
[0;0;0]
[0;1]
[0;1;1;0;0]
[0;2]
[0;8;1;0;0]
[0;9;1;0;0]
[0;10]
[0;10;1;0;0]
[1;0]
[1;1]
[2;1]
[2;10]
[3;1]
[3;1;2]
[3;1;4]

我的问题是如何通过索引有效地获取对象组。例如,我想检索具有第一个索引为 0 的键和索引以两个 2 开头的另一个组的所有对象。第一个想法是我可以创建一个哈希集,然后在将对象插入字典时对它们进行分组,但是我真的不认为它是有效的:

    HashSet<int> hash = new HashSet<int>();
    Dictionary<int, List<string>> groups = new Dictionary<int, List<string>>();

    public void Add(Element item) {

        string key = item.GetKey();
        sortedPlates.Add(key, item);


        int firstID = item.KeyToIntArray()[0];
        if (hash.Add(firstID)) 
            groups.Add(firstID,new List<string> { key });
        else 
            groups[firstID].Add(key );

    }

有什么方法可以直接访问组而不循环?我需要添加另一个属性来跟踪组吗?我觉得这种双循环对于非常大量的对象效率不高。

标签: c#sortedlist

解决方案


推荐阅读