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

时间:2013-09-10 10:31:16

标签: c#

我有一本现在的词典

如何通过在c#

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

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

3 个答案:

答案 0 :(得分:3)

字典未订购,您可以订购字典,然后选择开始和结束索引之间的项目,如下所示

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>并对其进行排序,您可以按索引选择项目。

答案 1 :(得分:1)

Dictionary课程未订购,您可以改用OrderedDictionary

答案 2 :(得分:0)

您可以使用以下代码获取字典范围:

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