c# - 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 );
}
有什么方法可以直接访问组而不循环?我需要添加另一个属性来跟踪组吗?我觉得这种双循环对于非常大量的对象效率不高。
解决方案
推荐阅读
- django - Django如何防止更新旧用户实例?
- python - Python pynput、pyautogui、键盘模块 - 无法将字母输入键盘,例如自动输入一个 setnence。记录输入工作正常
- android - 创建多个嵌套集合firestore android
- android - 为什么 paging3 与 Mediator 加载 APPEND 无限
- objective-c - [NSPlaceholderString initWithValidatedFormat:validFormatSpecifiers:locale:arguments:error
- peoplesoft - 从动态视图中提取记录时,为什么 Peoplesoft 组件接口会出错?
- r - 创建具有均值、标准差、标准误差和置信度误差的数据框
- python - InvalidArgumentError:您必须为占位符张量输入一个值,即使我输入了它
- r - 包是否在 R 中有 dll 的信息
- json - jq - 按字段值对 json 对象进行分组,并在一行中输出分组值