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
3
  • 4
    What do you expect the first item to be? Commented Jul 28, 2014 at 14:14
  • 1
    why use a dictionary then? Would an array or list not do the job? Commented Jul 28, 2014 at 14:15
  • Could you explain if you don't know how to loop over a dictionary or if you have problem to refer to a specific entry in the Dictionary without knowing the key value? Commented Jul 28, 2014 at 14:23

7 Answers 7

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”?

Sign up to request clarification or add additional context in comments.

7 Comments

who upvotes this? "how to loop through items" and you say "use first"? this answer is wrong
@AndreasMüller: i understood "item[0]" as "give me the first item" and "loop trough items" as "use it as collection".
@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
@AndreasMüller: how do you know? OP is trying to find 0(int) as key even if he adds DateTimes (as string)? Isn't that more unlikely as that he wants the first?
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
|
3

try this

  foreach (string key in selectedDates.Keys)
  {
        var item = selectedDates[key]; 
  }

1 Comment

though this is an amuzing way to do it, wouldn't a foreach(var v in sselectedDates){ var date = v.Value;} be better?
2

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

var date = selectedDates.ElementAt(0).Value;

Comments

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).

Comments

1

try this :

foreach(var key in selectedDates.Keys)
{
    var value = selectedDates[key];
}

1 Comment

As Vincent already commented at nsgocev's answer: "wouldn't a foreach(var v in sselectedDates){ var date = v.Value;} be better?"
0

Use this overload of Where:

var result = selectedDates.Where((d,i)=>i==0);

Comments

0

Try:

foreach (var date in selectedDates)                
{                  
    var item = date.Value;              
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.