views:

73

answers:

4

I have done a program

string[] arrExposureValues = stock.ExposureCollection[dt].Values.ToArray();
for(int i = 0; i < arrExposureValues.Length; i++)
    Console.WriteLine(arrExposureValues[i]);

Nothing wrong and works fine.

But is it possible to do something like the below

for(int i = 0; i < stock.ExposureCollection[dt].Count; i++)    
    Console.WriteLine(stock.ExposureCollection[dt].Values[i]);

This is just for my sake of knowledge (Basically trying to accomplish the same in one line).

Note: ExposureCollection is Dictionary<DateTime, Dictionary<string, string>>

First of all I have the doubt if it is at all possible!

I am using C# 3.0.

Thanks.

A: 

Try SortedList - it has properties like Values and Keys which you can index.

Voice
+1  A: 

You could enumerate over the stock.ExposureCollection[dt].Keys list using a foreach.

foreach( string key in stock.ExposureCollection[dt].Keys ) {
  Console.WriteLine(stock.ExposureCollection[dt][key]);
}
CERIQ
+1 for avoiding nested loops
Enrico Campidoglio
@Enrico Campidoglio: Here there are 3 spare loops! Also inner key isn't abaliable
abatishchev
@abatishchev Could you develop your point?
Enrico Campidoglio
@Enrico Campidoglio: 1st and 2nd spare loops are in `ExposureCollection[dt]` - it's better to cache it out of the loop. And 3rd - in `[key]` - because first you loop to iterate Keys and second - to find value by key. ForEach'ing Dictionary not Dictionary.Keys gives KeyValuePair which already contains both Key and Value in one loop.
abatishchev
@abatishchev: Looking up a value in a dictionary is a O(1) operation, since it's a hashmap. The Keys is simply a list of strings. This example is O(n).
CERIQ
@abatischev: You're actually partly right when I look it over again. I do look up the exposurecollection once in the head, and then once for every iteration, so it's actually a O(1+2n). Sorry about that.
CERIQ
@abatishchev As @CERIQ says, there's no loop involved in performing a lookup operation in a hashtable. Moreover in the Big O notation all constant factors can be ignored, so the algorithm is still O(n). However you are absolutely right saying that iterating through the dictionary will return both the key and the value, so that would simplify the algorithm.
Enrico Campidoglio
+1  A: 

First of all, what is you task? Enumerate dictionary and enumerate inner dictionary in the same time?

foreach(var item in dic)
{
    foreach(var inner in item.Value)
    {
        Console.WriteLine("key={0}, inner key={1}, inner value={2}",
            item.Key, inner.Key, inner.Value);
    }
}
abatishchev
A: 
for(int i = 0; i < stock.ExposureCollection[dt].Count; i++)     
    Console.WriteLine(stock.ExposureCollection[dt].Values.ElementAt(i)); 
Newbie