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
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”?
try this
foreach (string key in selectedDates.Keys)
{
var item = selectedDates[key];
}
try this :
foreach(var key in selectedDates.Keys)
{
var value = selectedDates[key];
}
It's simple, loop trough it with a foreach
or to get a specific index do:
var date = selectedDates.ElementAt(0).Value;
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With