I have this code:
SortedList<int, SortedList<int, SimulationPoint>> sl = new SortedList<int, SortedList<int, SimulationPoint>>();
for(int i=0; i<source.Reflections+1; i++)
{
sl.Add(i, new SortedList<int, SimulationPoint>());
}
var q = source.SimulationResult.Where(x => !x.Value.hasHit);
foreach (var qa in q)
{
sl[qa.Key.Item2].Add(qa.Key.Item1, qa.Value);
}
I wanted to generate a sorted output of the collection source.SimulationResult, which is a Dictionary<(int, int), SimulationPoint>. (This dictionary was generated using a Parallel.For() loop, so all the items are in random order.)
Dictionary Key: Just the Ray number emitted from the source (e.g. 0->100) and the Reflection number (e.g. 0->10) as it bounces around the scene: (int Ray, int Reflection).
Dictionary Value:
The SimulationPoint is an output point of a ray-tracing procedure, the most important element of which is that it contains a field bool hasHit that indicates if the point, well, hit an element in the scene or not. (We're looking for those errors here, hence source.SimulationResult.Where(x=>!x.Value.hashit);) (FWIW, this struct SimulationPoint also contains the Ray & Reflection data.)
Generally, this works. But I really like the LINQ syntax and one-liner concept, as it can avoid multiple nested loops. Does anyone have an idea how this can be simplified using the LINQ extensions?
Please keep in mind that I'd like to be able to jump around at the user's choice within the sl collection, this is the problem I'm having with the IGrouping<int, SimulationPoint> outputs from the GroupBy(x=>x.Key.Item2, x=>x.Value) method - it's only accessible sequentially using a foreach loop, even when ordering it with OrderBy(x.Key.Item2).ThenBy(x.Key.Item1).
So I sorted it out myself. It turns out I didn't need the SortedLists(s) at all, and since I have access to both the key.reflection and key.ray, I can just access the SimulationPoint directly from the source.SimulationResult dictionary.
So, in the end, all I needed was a List<List<int>> which is generated like this:
for (int i = 0; i < maxrays; i++)
sl.Add(new List<int>());
foreach (var q in source.SimulationResult.Where(x => !x.Value.hasHit))
sl[q.Key.Item2].Add(q.Key.Item1);
for (int i = 0; i < maxrays; i++)
sl[i].Sort();
It does make multiple loops, but that seemed unavoidable. The possibly empty child lists are necessary for other processing functions, and to save time, that's why they're all made at once rather than checking if they exist while going through the foreach loop. Then, because I want the child list in order, just calling List<T>.Source() works great, rather than trying to get LINQ to do it.
I suggest adding an extension method (group) analogous to ToDictionary to do ToSortedList. Then with that extension method available, you can use GroupBy (which is internally creating a Dictionary...) to create the SortedLists. Internally you are essentially running over the source data twice, but it doesn't seem like you are talking about a lot of data.
var sl2 = q.GroupBy(kvp => kvp.Key.Reflection) // group by outer SortedList Key
.ToSortedList(kvpg => kvpg.Key, // outer SortedList Key (Reflection)
// outer SortedList Value (SortedList: Ray -> SimulationPoint)
kvpg => kvpg.ToSortedList(kvp => kvp.Key.Ray, // inner SortedList Key (Ray)
kvp => kvp.Value) // inner SortedList Value (SimulationPoint)
);
Here are the extension method definitions:
public static class IEnumerableExt {
public static SortedList<TKey, TValue> ToSortedList<TItem, TKey, TValue>(this IEnumerable<TItem> items, Func<TItem, TKey> keyFn, Func<TItem, TValue> valueFn) {
var ans = new SortedList<TKey, TValue>();
foreach (var item in items)
ans.Add(keyFn(item), valueFn(item));
return ans;
}
public static SortedList<TKey, TValue> ToSortedList<TKey, TValue>(this IEnumerable<TValue> items, Func<TValue, TKey> keyFn) {
var ans = new SortedList<TKey, TValue>();
foreach (var item in items)
ans.Add(keyFn(item), item);
return ans;
}
public static SortedList<TKey, TKey> ToSortedList<TKey>(this IEnumerable<TKey> items) {
var ans = new SortedList<TKey, TKey>();
foreach (var item in items)
ans.Add(item, item);
return ans;
}
}
I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
Or, if you only need to iterate over the collection of keys, use
foreach(var item in myDictionary.Keys)
{
foo(item);
}
And lastly, if you're only interested in the values:
foreach(var item in myDictionary.Values)
{
foo(item);
}
(Take note that the var keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)
In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt which enables the following:
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
Depends on whether you're after the keys or the values...
From the MSDN Dictionary(TKey, TValue) Class description:
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}
Generally, asking for "the best way" without a specific context is like asking
what is the best color?
One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.
On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.
Most straightforward way
foreach (var kvp in items)
{
// key is kvp.Key
doStuff(kvp.Value)
}
If you need only the value (allows to call it item, more readable than kvp.Value).
foreach (var item in items.Values)
{
doStuff(item)
}
If you need a specific sort order
Generally, beginners are surprised about order of enumeration of a Dictionary.
LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:
foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
// key is kvp.Key
doStuff(kvp.Value)
}
Again you might only need the value. LINQ also provides a concise solution to:
iterate directly on the value (allows to call it item, more readable than kvp.Value)
but sorted by the keys
Here it is:
foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
doStuff(item)
}
There are many more real-world use case you can do from these examples.
If you don't need a specific order, just stick to the "most straightforward way" (see above)!
C# 7.0 introduced Deconstructors and if you are using .NET Core 2.0+ Application, the struct KeyValuePair<> already include a Deconstruct() for you. So you can do:
var dic = new Dictionary<int, string>() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (var (key, value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
//Or
foreach (var (_, value) in dic) {
Console.WriteLine($"Item [NO_ID] = {value}");
}
//Or
foreach ((int key, string value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
I would say foreach is the standard way, though it obviously depends on what you're looking for
foreach(var kvp in my_dictionary) {
...
}
Is that what you're looking for?
You can also try this on big dictionaries for multithreaded processing.
dictionary
.AsParallel()
.ForAll(pair =>
{
// Process pair.Key and pair.Value here
});
I appreciate this question has already had a lot of responses but I wanted to throw in a little research.
Iterating over a dictionary can be rather slow when compared with iterating over something like an array. In my tests an iteration over an array took 0.015003 seconds whereas an iteration over a dictionary (with the same number of elements) took 0.0365073 seconds that's 2.4 times as long! Although I have seen much bigger differences. For comparison a List was somewhere in between at 0.00215043 seconds.
However, that is like comparing apples and oranges. My point is that iterating over dictionaries is slow.
Dictionaries are optimised for lookups, so with that in mind I've created two methods. One simply does a foreach, the other iterates the keys then looks up.
public static string Normal(Dictionary<string, string> dictionary)
{
string value;
int count = 0;
foreach (var kvp in dictionary)
{
value = kvp.Value;
count++;
}
return "Normal";
}
This one loads the keys and iterates over them instead (I did also try pulling the keys into a string[] but the difference was negligible.
public static string Keys(Dictionary<string, string> dictionary)
{
string value;
int count = 0;
foreach (var key in dictionary.Keys)
{
value = dictionary[key];
count++;
}
return "Keys";
}
With this example the normal foreach test took 0.0310062 and the keys version took 0.2205441. Loading all the keys and iterating over all the lookups is clearly a LOT slower!
For a final test I've performed my iteration ten times to see if there are any benefits to using the keys here (by this point I was just curious):
Here's the RunTest method if that helps you visualise what's going on.
private static string RunTest<T>(T dictionary, Func<T, string> function)
{
DateTime start = DateTime.Now;
string name = null;
for (int i = 0; i < 10; i++)
{
name = function(dictionary);
}
DateTime end = DateTime.Now;
var duration = end.Subtract(start);
return string.Format("{0} took {1} seconds", name, duration.TotalSeconds);
}
Here the normal foreach run took 0.2820564 seconds (around ten times longer than a single iteration took - as you'd expect). The iteration over the keys took 2.2249449 seconds.
Edited To Add:
Reading some of the other answers made me question what would happen if I used Dictionary instead of Dictionary. In this example the array took 0.0120024 seconds, the list 0.0185037 seconds and the dictionary 0.0465093 seconds. It's reasonable to expect that the data type makes a difference on how much slower the dictionary is.
What are my Conclusions?
Avoid iterating over a dictionary if you can, they are substantially slower than iterating over an array with the same data in it.
If you do choose to iterate over a dictionary don't try to be too clever, although slower you could do a lot worse than using the standard foreach method.
As already pointed out on this answer, KeyValuePair<TKey, TValue> implements a Deconstruct method starting on .NET Core 2.0, .NET Standard 2.1 and .NET Framework 5.0 (preview).
With this, it's possible to iterate through a dictionary in a KeyValuePair agnostic way:
var dictionary = new Dictionary<int, string>();
// ...
foreach (var (key, value) in dictionary)
{
// ...
}
There are plenty of options. My personal favorite is by KeyValuePair
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary)
{
// Do some interesting things
}
You can also use the Keys and Values Collections
With .NET Framework 4.7 one can use decomposition
var fruits = new Dictionary<string, int>();
...
foreach (var (fruit, number) in fruits)
{
Console.WriteLine(fruit + ": " + number);
}
To make this code work on lower C# versions, add System.ValueTuple NuGet package and write somewhere
public static class MyExtensions
{
public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple,
out T1 key, out T2 value)
{
key = tuple.Key;
value = tuple.Value;
}
}
As of C# 7, you can deconstruct objects into variables. I believe this to be the best way to iterate over a dictionary.
Example:
Create an extension method on KeyValuePair<TKey, TVal> that deconstructs it:
public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value)
{
key = pair.Key;
value = pair.Value;
}
Iterate over any Dictionary<TKey, TVal> in the following manner
// Dictionary can be of any types, just using 'int' and 'string' as examples.
Dictionary<int, string> dict = new Dictionary<int, string>();
// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
Console.WriteLine($"{key} : {value}");
}
foreach is fastest and if you only iterate over ___.Values, it is also faster
Using C# 7, add this extension method to any project of your solution:
public static class IDictionaryExtensions
{
public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
this IDictionary<TKey, TValue> dict)
{
foreach (KeyValuePair<TKey, TValue> kvp in dict)
yield return (kvp.Key, kvp.Value);
}
}
And use this simple syntax
foreach (var(id, value) in dict.Tuples())
{
// your code using 'id' and 'value'
}
Or this one, if you prefer
foreach ((string id, object value) in dict.Tuples())
{
// your code using 'id' and 'value'
}
In place of the traditional
foreach (KeyValuePair<string, object> kvp in dict)
{
string id = kvp.Key;
object value = kvp.Value;
// your code using 'id' and 'value'
}
The extension method transforms the KeyValuePair of your IDictionary<TKey, TValue> into a strongly typed tuple, allowing you to use this new comfortable syntax.
It converts -just- the required dictionary entries to tuples, so it does NOT converts the whole dictionary to tuples, so there are no performance concerns related to that.
There is a only minor cost calling the extension method for creating a tuple in comparison with using the KeyValuePair directly, which should NOT be an issue if you are assigning the KeyValuePair's properties Key and Value to new loop variables anyway.
In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.
Check this out: MSDN Blog - New features in C# 7
Simplest form to iterate a dictionary:
foreach(var item in myDictionary)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
I found this method in the documentation for the DictionaryBase class on MSDN:
foreach (DictionaryEntry de in myDictionary)
{
//Do some stuff with de.Value or de.Key
}
This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.
Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:
foreach(var value in dictionary.Values)
{
// do something with entry.Value only
}
Reported by this post which states it is the fastest method:
http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html
I know this is a very old question, but I created some extension methods that might be useful:
public static void ForEach<T, U>(this Dictionary<T, U> d, Action<KeyValuePair<T, U>> a)
{
foreach (KeyValuePair<T, U> p in d) { a(p); }
}
public static void ForEach<T, U>(this Dictionary<T, U>.KeyCollection k, Action<T> a)
{
foreach (T t in k) { a(t); }
}
public static void ForEach<T, U>(this Dictionary<T, U>.ValueCollection v, Action<U> a)
{
foreach (U u in v) { a(u); }
}
This way I can write code like this:
myDictionary.ForEach(pair => Console.Write($"key: {pair.Key}, value: {pair.Value}"));
myDictionary.Keys.ForEach(key => Console.Write(key););
myDictionary.Values.ForEach(value => Console.Write(value););
If you want to use a for loop, you can do as below:
var keyList=new List<string>(dictionary.Keys);
for (int i = 0; i < keyList.Count; i++)
{
var key= keyList[i];
var value = dictionary[key];
}
I will take the advantage of .NET 4.0+ and provide an updated answer to the originally accepted one:
foreach(var entry in MyDic)
{
// do something with entry.Value or entry.Key
}
If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.
public new IEnumerator<T> GetEnumerator()
{
return this.Values.GetEnumerator();
}
The standard way to iterate over a Dictionary, according to official documentation on MSDN is:
foreach (DictionaryEntry entry in myDictionary)
{
//Read entry.Key and entry.Value here
}
I wrote an extension to loop over a dictionary.
public static class DictionaryExtension
{
public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {
foreach(KeyValuePair<T1, T2> keyValue in dictionary) {
action(keyValue.Key, keyValue.Value);
}
}
}
Then you can call
myDictionary.ForEach((x,y) => Console.WriteLine(x + " - " + y));
Dictionary< TKey, TValue > It is a generic collection class in c# and it stores the data in the key value format.Key must be unique and it can not be null whereas value can be duplicate and null.As each item in the dictionary is treated as KeyValuePair< TKey, TValue > structure representing a key and its value. and hence we should take the element type KeyValuePair< TKey, TValue> during the iteration of element.Below is the example.
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");
foreach (KeyValuePair<int, string> item in dict)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
The best answer is of course: Think, if you could use a more appropriate data structure than a dictionary if you plan to iterate over it- as Vikas Gupta mentioned already in the (beginning of the) discussion under the question. But that discussion as this whole thread still lacks surprisingly good alternatives. One is:
SortedList<string, string> x = new SortedList<string, string>();
x.Add("key1", "value1");
x.Add("key2", "value2");
x["key3"] = "value3";
foreach( KeyValuePair<string, string> kvPair in x )
Console.WriteLine($"{kvPair.Key}, {kvPair.Value}");
Why it could be argued a code smell of iterating over a dictionary (e.g. by foreach(KeyValuePair<,>) ?
A basic principle of Clean Coding:
"Express intent!"
Robert C. Martin writes in "Clean Code": "Choosing names that reveal intent". Obviously naming alone is too weak. "Express (reveal) intent with every coding decision" expresses it better.
A related principle is "Principle of least surprise" (=Principle of Least Astonishment).
Why this is related to iterating over a dictionary? Choosing a dictionary expresses the intent of choosing a data structure which was made for primarily finding data by key. Nowadays there are so much alternatives in .NET, if you want to iterate through key/value pairs that you could choose something else.
Moreover: If you iterate over something, you have to reveal something about how the items are (to be) ordered and expected to be ordered!
Although the known implementations of Dictionary sort the key collection in the order of the items added-
AFAIK, Dictionary has no assured specification about ordering (has it?).
But what are the alternatives?
TLDR:
SortedList: If your collection is not getting too large, a simple solution would be to use SortedList<,> which gives you also full indexing of key/value pairs.
Microsoft has a long article about mentioning and explaining fitting collections:
Keyed collection
To mention the most important: KeyedCollection<,> and SortedDictionary<,> .
SortedDictionary<,> is a bit faster than SortedList for only inserting if it gets large, but lacks indexing and is needed only if O(log n) for inserting is preferenced over other operations. If you really need O(1) for inserting and accept slower iterating in exchange, you have to stay with simple Dictionary<,>.
Obviously there is no data structure which is the fastest for every possible operation..
Additionally there is ImmutableSortedDictionary<,>.
And if one data structure is not exactly what you need, then derivate from Dictionary<,> or even from the new ConcurrentDictionary<,> and add explicit iteration/sorting functions!
var dictionary = new Dictionary<string, int>
{
{ "Key", 12 }
};
var aggregateObjectCollection = dictionary.Select(
entry => new AggregateObject(entry.Key, entry.Value));
Just wanted to add my 2 cent, as the most answers relate to foreach-loop.
Please, take a look at the following code:
Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();
//Add some entries to the dictionary
myProductPrices.ToList().ForEach(kvP =>
{
kvP.Value *= 1.15;
Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));
});
Altought this adds a additional call of '.ToList()', there might be a slight performance-improvement (as pointed out here foreach vs someList.Foreach(){}),
espacially when working with large Dictionaries and running in parallel is no option / won't have an effect at all.
Also, please note that you wont be able to assign values to the 'Value' property inside a foreach-loop. On the other hand, you will be able to manipulate the 'Key' as well, possibly getting you into trouble at runtime.
When you just want to "read" Keys and Values, you might also use IEnumerable.Select().
var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );
in addition to the highest ranking posts where there is a discussion between using
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
or
foreach(var entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
most complete is the following because you can see the dictionary type from the initialization, kvp is KeyValuePair
var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x
foreach(var kvp in myDictionary)//iterate over dictionary
{
// do something with kvp.Value or kvp.Key
}
I'm using a Dictionary<string, int> where the int is a count of the key.
Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:
int LastCount = mydict[mydict.keys[mydict.keys.Count]];
does not work, because Dictionary.Keys does not implement a []-indexer.
I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?
As #Falanwe points out in a comment, doing something like this is incorrect:
int LastCount = mydict.Keys.ElementAt(mydict.Count -1);
You should not depend on the order of keys in a Dictionary. If you need ordering, you should use an OrderedDictionary, as suggested in this answer. The other answers on this page are interesting as well.
You can use an OrderedDictionary.
Represents a collection of key/value
pairs that are accessible by the key
or index.
A Dictionary is a Hash Table, so you have no idea the order of insertion!
If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.
E.g.:
public MyDictionary<K, T> : IDictionary<K, T>
{
private IDictionary<K, T> _InnerDictionary;
public K LastInsertedKey { get; set; }
public MyDictionary()
{
_InnerDictionary = new Dictionary<K, T>();
}
#region Implementation of IDictionary
public void Add(KeyValuePair<K, T> item)
{
_InnerDictionary.Add(item);
LastInsertedKey = item.Key;
}
public void Add(K key, T value)
{
_InnerDictionary.Add(key, value);
LastInsertedKey = key;
}
.... rest of IDictionary methods
#endregion
}
You will run into problems however when you use .Remove() so to overcome this you will have to keep an ordered list of the keys inserted.
Why don't you just extend the dictionary class to add in a last key inserted property. Something like the following maybe?
public class ExtendedDictionary : Dictionary<string, int>
{
private int lastKeyInserted = -1;
public int LastKeyInserted
{
get { return lastKeyInserted; }
set { lastKeyInserted = value; }
}
public void AddNew(string s, int i)
{
lastKeyInserted = i;
base.Add(s, i);
}
}
You could always do this:
string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]
But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys on MSDN is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.
I think you can do something like this, the syntax might be wrong, havent used C# in a while
To get the last item
Dictionary<string, int>.KeyCollection keys = mydict.keys;
string lastKey = keys.Last();
or use Max instead of Last to get the max value, I dont know which one fits your code better.
I agree with the second part of Patrick's answer. Even if in some tests it seems to keep insertion order, the documentation (and normal behavior for dictionaries and hashes) explicitly states the ordering is unspecified.
You're just asking for trouble depending on the ordering of the keys. Add your own bookkeeping (as Patrick said, just a single variable for the last added key) to be sure. Also, don't be tempted by all the methods such as Last and Max on the dictionary as those are probably in relation to the key comparator (I'm not sure about that).
In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a Dictionary<K,V> according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the Keys property).
It is much preferable to use Linq: dict.Keys.ElementAt(i), but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.
using System;
using System.Collections.Generic;
using System.Reflection;
public static class Extensions
{
public static TKey KeyByIndex<TKey,TValue>(this Dictionary<TKey, TValue> dict, int idx)
{
Type type = typeof(Dictionary<TKey, TValue>);
FieldInfo info = type.GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance);
if (info != null)
{
// .NET
Object element = ((Array)info.GetValue(dict)).GetValue(idx);
return (TKey)element.GetType().GetField("key", BindingFlags.Public | BindingFlags.Instance).GetValue(element);
}
// Mono:
info = type.GetField("keySlots", BindingFlags.NonPublic | BindingFlags.Instance);
return (TKey)((Array)info.GetValue(dict)).GetValue(idx);
}
};
One alternative would be a KeyedCollection if the key is embedded in the value.
Just create a basic implementation in a sealed class to use.
So to replace Dictionary<string, int> (which isn't a very good example as there isn't a clear key for a int).
private sealed class IntDictionary : KeyedCollection<string, int>
{
protected override string GetKeyForItem(int item)
{
// The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
return item.ToString();
}
}
KeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();
intCollection.Add(7);
int valueByIndex = intCollection[0];
The way you worded the question leads me to believe that the int in the Dictionary contains the item's "position" on the Dictionary. Judging from the assertion that the keys aren't stored in the order that they're added, if this is correct, that would mean that keys.Count (or .Count - 1, if you're using zero-based) should still always be the number of the last-entered key?
If that's correct, is there any reason you can't instead use Dictionary<int, string> so that you can use mydict[ mydict.Keys.Count ]?
I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.
The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.
To expand on Daniels post and his comments regarding the key, since the key is embedded within the value anyway, you could resort to using a KeyValuePair<TKey, TValue> as the value. The main reasoning for this is that, in general, the Key isn't necessarily directly derivable from the value.
Then it'd look like this:
public sealed class CustomDictionary<TKey, TValue>
: KeyedCollection<TKey, KeyValuePair<TKey, TValue>>
{
protected override TKey GetKeyForItem(KeyValuePair<TKey, TValue> item)
{
return item.Key;
}
}
To use this as in the previous example, you'd do:
CustomDictionary<string, int> custDict = new CustomDictionary<string, int>();
custDict.Add(new KeyValuePair<string, int>("key", 7));
int valueByIndex = custDict[0].Value;
int valueByKey = custDict["key"].Value;
string keyByIndex = custDict[0].Key;
A dictionary may not be very intuitive for using index for reference but, you can have similar operations with an array of KeyValuePair:
ex.
KeyValuePair<string, string>[] filters;
You can also use SortedList and its Generic counterpart. These two classes and in Andrew Peters answer mentioned OrderedDictionary are dictionary classes in which items can be accessed by index (position) as well as by key. How to use these classes you can find: SortedList Class , SortedList Generic Class .
Visual Studio's UserVoice gives a link to generic OrderedDictionary implementation by dotmore.
But if you only need to get key/value pairs by index and don't need to get values by keys, you may use one simple trick. Declare some generic class (I called it ListArray) as follows:
class ListArray<T> : List<T[]> { }
You may also declare it with constructors:
class ListArray<T> : List<T[]>
{
public ListArray() : base() { }
public ListArray(int capacity) : base(capacity) { }
}
For example, you read some key/value pairs from a file and just want to store them in the order they were read so to get them later by index:
ListArray<string> settingsRead = new ListArray<string>();
using (var sr = new StreamReader(myFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] keyValueStrings = line.Split(separator);
for (int i = 0; i < keyValueStrings.Length; i++)
keyValueStrings[i] = keyValueStrings[i].Trim();
settingsRead.Add(keyValueStrings);
}
}
// Later you get your key/value strings simply by index
string[] myKeyValueStrings = settingsRead[index];
As you may have noticed, you can have not necessarily just pairs of key/value in your ListArray. The item arrays may be of any length, like in jagged array.