How do I get the nth element from a Dictionary?

cipher = new Dictionary<char,int>; cipher.Add( 'a', 324 ); cipher.Add( 'b', 553 ); cipher.Add( 'c', 915 );

How to get the 2nd element? For example, I'd like something like:

KeyValuePair pair = cipher[1]

where pair contains ( 'b', 553 )


Based on thecoop's suggestion using a List, things are workking:

List<KeyValuePair<char, int>> cipher = new List<KeyValuePair<char, int>>(); cipher.Add( new KeyValuePair<char, int>( 'a', 324 ) ); cipher.Add( new KeyValuePair<char, int>( 'b', 553 ) ); cipher.Add( new KeyValuePair<char, int>( 'c', 915 ) ); KeyValuePair<char, int> pair = cipher[ 1 ];

Assuming that I'm correct that the items stay in the list in the order that they are added, I belive that I can just use a List as opposed to a SortedList as suggested.



The problem is a Dictionary isn't sorted. What you want is a SortedList, which allows you to get values by index as well as key, although you may need to specify your own comparer in the constructor to get the sorting you want. You can then access an ordered list of the Keys and Values, and use various combinations of the IndexOfKey/IndexOfValue methods as needed.

like this:

int n = 0;
int nthValue = cipher[cipher.Keys.ToList()[n]];

note that you will also need a reference to Linq at the top of your page...

using System.Linq;

Do you actually need to look up by the key? If not, use a List<KeyValuePair<char, int>> (or better yet, create a type to encapsulate the char and the int).

Dictionaries aren't inherently sorted - the dictionary implementations which are sorted in .NET are sorted by key, not by insertion order.

If you need to access the collection by both insertion order and key, I'd recommend encapsulating a List and a Dictionary in a single collection type.

Alternatively, if the list is going to be quite short, allow lookup by index just by doing a linear search...

Just to cling to your original spec for a Dictionary, I slung some code and came up with:

Dictionary<string, string> d = new Dictionary<string, string>();

d.Add("a", "apple");
d.Add("b", "ball");
d.Add("c", "cat");
d.Add("d", "dog");

int t = 0;
foreach (string s in d.Values)
if (t == 2) Console.WriteLine(s);

and it does seem to write the second item ("ball") to the console repeatably. If you wrapped it into a method call to get the nth element, it would probably work. This is pretty ugly, though. If you could do a SortedList instead, as @thecoop suggests, you'd be better off.

There was a dupe of this question asked here: How to retrieve Nth item in dictionary?. It should be closed soon, but I noticed that the answers here are missing the new OrderedDictionary class.

There is now (as of .NET 4), an OrderedDictionary class. This allows fast lookups while providing ordering. The Item(Int32) method returns the nth element.

Do NOT try this: This was a dumb idea - sorry guys!


'cause the 2ND element is index 1!

Category:c# Time:2009-07-23 Views:1
Tags: c# dictionary

Related post

  • How to access nth element through CSS in IE6+7 2009-04-15

    I want to know how we can access nth element of an <li> using CSS in IE6/IE7. HTML: <ul class="myUL"> <li><a href="" target="">Link1</a></li> <li><a href="">Link2</a></li> <li><a hr

  • How to get every Nth element of an infinite list in Haskell? 2010-01-08

    More specifically, how do I generate a new list of every Nth element from an existing infinite list? E.g. if the list is [5, 3, 0, 1, 8, 0, 3, 4, 0, 93, 211, 0 ...] then getting every 3rd element would result in this list [0,0,0,0,0 ...] ------------

  • How to get the nth element of a python list or a default if not available 2010-03-22

    I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available? For example, given a list myList I would like to get myList[0], or 5

  • Prolog: Finding the Nth Element in a List 2010-04-06

    I am attempting to locate the nth element of a List in Prolog. Here is the code I am attempting to use: Cells = [OK, _, _, _, _, _] . ... next_safe(_) :- facing(CurrentDirection), delta(CurrentDirection, Delta), in_cell(OldLoc), NewLoc is OldLoc + De

  • Is there a common lisp macro for popping the nth element from a list? 2010-11-04

    I'm pretty fresh to the Common Lisp scene and I can't seem to find an quick way to get the nth element from a list and remove it from said list at the same time. I've done it, but it ain't pretty, what I'd really like is something like "pop" but took

  • Any way to select nth element STRAIGHT? 2010-11-16

    Well, there are so many new css selectors, but I can't figure out a way of selecting nth-element or last-element or first-element. It's supported and it works, but only for children, for example: <div> <p>One</p> <p>Two</p

  • Getting every nth Element of a Sequence 2011-01-13

    I am looking for a way to create a sequence consisting of every nth element of another sequence, but don't seem to find a way to do that in an elegant way. I can of course hack something, but I wonder if there is a library function that I'm not seein

  • std::map with efficient nth element access 2011-01-14

    I've got a set of data that I need to store in an ordered map (i.e. with efficient insertion, deletion, and locating items by key), but I also need to be able to find the nth element without walking through the entire map (there may sometimes be tens

  • Remove every nth element from string 2011-03-13

    How can you remove every nth element of a string? I'm guessing you would use the drop function in some kind of way. Like this drops the first n, how can you change this so only drops the nth, and then the nth after that, and so on, rather than all? d

  • Changing the nth element of a list 2011-05-19

    I want change the nth element of a list and return a new list. I've thought of three rather inelegant solutions: (defun set-nth1 (list n value) (let ((list2 (copy-seq list))) (setf (elt list2 n) value) list2)) (defun set-nth2 (list n value) (concaten

  • the fastest way to pick the Nth element of a hash 2011-06-07

    I've got a big hashtable (array with string indexes) and looking for a function that quickly picks the first (ideally, also Nth) element from it. array_shift() and reset() are too slow for my needs. UPDATE: i'm also not looking for a reference-based

  • Selecting every Nth element from a large MongoDB collection w/ PHP? 2011-06-12

    I have a MongoDB collection with ~4M elements. I want to grab X number of those elements, evenly spaced through the entire collection. E.g., Get 1000 elements from the collection - one every 4000 rows. Right now, I am getting the whole collection in

  • Query for every nth element in core data 2011-07-31

    How do I query for every nTh (or just every second) Element in Core Data? Here is what I would do in SQL: SELECT * FROM TABLE_NAME WHERE (ROWID, 0) IN (SELECT ROWID, MOD(ROWID, N) FROM TABLE_NAME); Thx in advance. --------------Solutions-------------

  • How to retrieve the nth element of a StringListProperty in AppEngine? 2011-08-05

    Is there a way to get the nth element in a String List Property in Appengine without using a for loop? Something like nameOfList[2] Thanks! --------------Solutions------------- These properties are lists, so all list methods apply. Try this on shell.

  • Oracle SQL getting the nth element regexp 2011-09-09

    I am trying to get the nth element in a comma separated string using SQL in Oracle. I have the following so far.. SELECT regexp_substr('100016154,5101884LT00001,,,,,100000010892100000012655,L,SEI,5101884LT00001,1,SL,3595.03,00,2,N,N,G,N','[^,]+',1,7)

  • Get the Nth element with XPath - when element[N] fails 2011-10-06

    There were already some discussion about the Nth element in XPath: XPath query to get nth instance of an element Get Nth child of a node using xpath XPath and PHP: Parse from the nth instance of an element I'm using Selenium and PHPUnit for funcional

  • MATLAB: extract every nth element of vector 2011-10-25

    Is there an easy way to extract every nth element of a vector in MATLAB? Say we have x = linspace(1,10,10); Is there a command something like y = nth(x,3) so that y = 3 6 9? Cheers! --------------Solutions------------- Try this: x = linspace(1, 10, 1

  • Selecting the nth-element of a X class 2011-12-12

    how can i select the nth-element of a X class , using only CSS 3 selectors. In specific i need to select each even table rows in a table to apply an style but sometimes i insert a table row that need to be ignored because isn't data i tried using tr.

  • Common Lisp: How to return a list without the nth element of a given list? 2012-02-25

    I've a question, how to return a list without the nth element of a given list? E.g., given list: (1 2 3 2 4 6), and given n = 4, in this case the return list should be (1 2 3 4 6). --------------Solutions------------- A simple recursive solution: (de

Copyright (C), All Rights Reserved.

processed in 3.012 (s). 13 q(s)