10

I have a:

var selectedDates = new Dictionary<string, string>();
selectedDates.Add("2014-06-21", DateTime.Now.ToLongDateString());
selectedDates.Add("2014-07-21", DateTime.Now.AddDays(5).ToLongDateString());
selectedDates.Add("2014-08-21", DateTime.Now.AddDays(9).ToLongDateString());
selectedDates.Add("2014-09-21", DateTime.Now.AddDays(14).ToLongDateString());

How can I loop trough items without knowing the key?

For example I want to get the value of the item[0]

If I do:

var item = selectedDates[0].value; // I get an error
VAAA
  • 14,531
  • 28
  • 130
  • 253

7 Answers7

9

How can I loop trough items without knowing the key?

For example I want to get the value of the item[0]

You want to treat the dictionary as (ordered) collection similar to a list or array and get the first item in it?

You can because a Dictionary<string, string> is an IEnumerable<KeyValuePair<string, string>> implicitly. Just use First or FirstOrDefault:

string valueAtFirstPosition = selectedDates.First().Value; 

However, note that a dictionary is not meant to be used as as an ordered collection. It is a collection which can be used to fast-lookup a value by a key. But you can enumerate it anyway.

foreach(KeyValuePair<string, string>keyVal in selectedDates)
{
    Console.WriteLine("Key: {0} Value: {1}", keyVal.Key, keyVal.Value);
}

You should simply not rely on that order. I think in the current implementation the order is stable as long as you don't delete items. Read

Read: Why is a Dictionary “not ordered”?

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • who upvotes this? "how to loop through items" and you say "use first"? this answer is wrong – Dbl Jul 28 '14 at 14:18
  • @AndreasMüller: i understood "item[0]" as "give me the first item" and "loop trough items" as "use it as collection". – Tim Schmelter Jul 28 '14 at 14:19
  • @TimeSchmelter question asks for something else. using [0] is OP's way of expressing that he doesn't know how to use a dictionary, and is refusing to read msdn api – Dbl Jul 28 '14 at 14:21
  • @AndreasMüller: how do you know? OP is trying to find `0`(`int`) as key even if he adds `DateTime`s (as `string`)? Isn't that more unlikely as that he wants the first? – Tim Schmelter Jul 28 '14 at 14:22
  • he is adding string keys and expects the indexer to work with an integer. No. If you're using a dictionary that's not what you would want. If he would want the first item he HOPEFULLY would be using a list instead – Dbl Jul 28 '14 at 14:25
  • @AndreasMüller: He doesnt expect it to work, he just wants to use it like a list if he wants to access the first. That's why i've mentioned that a dictionary is not meant to be used as as an ordered collection. However, the order is stable as long as you don't modify the dictionary later (to be exact: delete items). – Tim Schmelter Jul 28 '14 at 14:28
  • fair enough. In this case you probably guessed his intentions correct and he just doesn't know what collection to use. – Dbl Jul 28 '14 at 14:30
3

try this

  foreach (string key in selectedDates.Keys)
  {
        var item = selectedDates[key]; 
  }
nsgocev
  • 4,390
  • 28
  • 37
  • 6
    though this is an amuzing way to do it, wouldn't a foreach(var v in sselectedDates){ var date = v.Value;} be better? – Vincent Jul 28 '14 at 14:20
2

It's simple, loop trough it with a foreach or to get a specific index do:

var date = selectedDates.ElementAt(0).Value;
Vincent
  • 1,497
  • 1
  • 21
  • 44
2

Let me put together two things for you. Firstly, you can loop or use LINQ to access elements, just as you could do it in a list as well:

var dict = new Dictionary<string, string>();

// loop
foreach (var item in dict)
{
    var key = item.Key;
    var value = item.Value;
}

// "first" (see below)
var firstItem = dict.First();

However, be aware that what you're referring to as the first item can be pretty much any item in the Dictionary. Dictionaries store elements in any order that is convenient for a lookup (so do sets).

This order is known for some implementations, but lists or arrays might fit better when the order of the elements is important. A Dictionary in .NET is an implementation of a hash table data structure (tree map is another map implementation).

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
1

try this :

foreach(var key in selectedDates.Keys)
{
    var value = selectedDates[key];
}
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
  • 1
    As Vincent already commented at nsgocev's answer: *"wouldn't a foreach(var v in sselectedDates){ var date = v.Value;} be better?"* –  Jul 28 '14 at 14:22
0

Use this overload of Where:

var result = selectedDates.Where((d,i)=>i==0);
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
0

Try:

foreach (var date in selectedDates)                
{                  
    var item = date.Value;              
}
JKennedy
  • 18,150
  • 17
  • 114
  • 198