loops - Iterate over C# dictionary's keys with index? -
how iterate on dictionary's keys while maintaining index of key. i've done merge foreach
-loop local variable i
gets incremented 1 every round of loop.
here's code works:
public iterateovermydict() { int i=-1; foreach (string key in mydict.keys) { i++; console.write(i.tostring() + " : " + key); } }
however, seems low tech use local variable i
. wondering if there's way don't have use "extra" variable? not saying bad way, there better one?
there's no such concept "the index of key". should treat dictionary<tkey, tvalue>
having unpredictable order - order happen when iterating on may change. (so in theory, add 1 new entry, , entries in different order next time iterated on them. in theory happen without changing data, that's less in normal implementations.)
if really want numeric index happened observe time, use:
foreach (var x in dictionary.select((entry, index) => new { entry, index })) { console.writeline("{0}: {1} = {2}", x.index, x.entry.key, x.entry.value); }
... aware that's misleading display, suggests inherent ordering.
from documentation:
for purposes of enumeration, each item in dictionary treated
keyvaluepair<tkey, tvalue>
structure representing value , key. order in items returned undefined.
edit: if don't select
call here, could create own extension method:
public struct indexedvalue<t> { private readonly t value; private readonly int index; public t value { { return value; } } public int index { { return index; } } public indexedvalue(t value, int index) { this.value = value; this.index = index; } } public static class extensions { public static ienumerable<indexedvalue<t>> withindex<t> (this ienumerable<t> source) { return source.select((value, index) => new indexedvalue<t>(value, index)); } }
then loop be:
foreach (var x in dictionary.withindex()) { console.writeline("{0}: {1} = {2}", x.index, x.value.key, x.value.value); }
Comments
Post a Comment