如何通过指定开始和结束索引从字典中获取一系列项目

本文关键字:字典 获取 项目 一系列 索引 结束 何通过 开始 | 更新日期: 2023-09-27 18:30:43

我现在有一本字典

如何通过在 c# 中指定开始和结束索引从字典中获取一系列项

基本上,我必须为我的字典元素实现分页以显示 5 个元素,然后单击下一步,我将显示接下来的 5 个项目,依此类推

如何通过指定开始和结束索引从字典中获取一系列项目

字典

不排序,您可以对字典进行排序,然后选择开始和结束索引之间的项目,如下所示

public Dictionary<string, myCustomType> GetData(int startIndex, int endIndex)
{
    return dictionary.OrderBy(d => d.Key).Skip(startIndex).Take(endIndex-startIndex +1).ToDictionary(k=>k.Key, v=>v.Value);
}

如果没有上述所有排序,您可以使用SortedList<string, myCustomType>而不是Dictionary<string, myCustomType>,并且它已排序,您可以按索引选择项目。

Dictionary类不是有序的,你可以改用OrderedDictionary

您可以使用

以下代码获取字典的范围:

foreach(KeyValuePair<string, string> entry in MyDic)
{
    // do something with entry.Value or entry.Key
}