Skip to main content
 首页 » 编程设计

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

2024年02月13日18youxin

我现在有一本字典

如何通过在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>它已排序,您可以按索引选择项目。