c# Dictionary<string,string> how to loop through items without knowing key [duplicate]
Asked Answered
B

7

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
Bigg answered 28/7, 2014 at 14:12 Comment(3)
What do you expect the first item to be?Inaccessible
why use a dictionary then? Would an array or list not do the job?Fane
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?Mestee
A
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”?

Asseveration answered 28/7, 2014 at 14:14 Comment(7)
who upvotes this? "how to loop through items" and you say "use first"? this answer is wrongEnyo
@AndreasMüller: i understood "item[0]" as "give me the first item" and "loop trough items" as "use it as collection".Asseveration
@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 apiEnyo
@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?Asseveration
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 insteadEnyo
@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).Asseveration
fair enough. In this case you probably guessed his intentions correct and he just doesn't know what collection to use.Enyo
S
3

try this

  foreach (string key in selectedDates.Keys)
  {
        var item = selectedDates[key]; 
  }
Shelving answered 28/7, 2014 at 14:14 Comment(1)
though this is an amuzing way to do it, wouldn't a foreach(var v in sselectedDates){ var date = v.Value;} be better?Impartial
I
2

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

var date = selectedDates.ElementAt(0).Value;
Impartial answered 28/7, 2014 at 14:17 Comment(0)
A
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).

Antediluvian answered 28/7, 2014 at 14:23 Comment(0)
S
1

try this :

foreach(var key in selectedDates.Keys)
{
    var value = selectedDates[key];
}
Stylographic answered 28/7, 2014 at 14:14 Comment(1)
As Vincent already commented at nsgocev's answer: "wouldn't a foreach(var v in sselectedDates){ var date = v.Value;} be better?"Zara
A
0

Use this overload of Where:

var result = selectedDates.Where((d,i)=>i==0);
Amidase answered 28/7, 2014 at 14:13 Comment(0)
M
0

Try:

foreach (var date in selectedDates)                
{                  
    var item = date.Value;              
}
Martell answered 28/7, 2014 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.