简体   繁体   中英

How to get a range of items from dictionary by specifying start and end index

I have a dictionary of now

How to get a range of items from dictionary by specifying start and end index in c#

Basically i have to implement paging for my dictionary elements as to show 5 elements then on click next i will show next 5 items and so on

Dictionaries aren't ordered, You can order your dictionary and then select the items between start and end index like below

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);
}

Without all above ordering you can use SortedList<string, myCustomType> instead of Dictionary<string, myCustomType> and it is sorted and you can select items by index.

Dictionary类没有排序,您可以使用OrderedDictionary

You can get the range of dictionary by using the below code :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM