tags:

views:

154

answers:

6

I have a dictionary of dictionaries, and I can't seem to figure out how to do a foreach loop on in the inner dictionary.

My collection:

Dictionary<int, Dictionary<int, User>>

So far I have:

foreach(User user in myDic[someKey]??)
+3  A: 
foreach (KeyValuePair<int, Dictionary<int, User>> users in myDic) {
    foreach (KeyValuePair<int, User> user in users.Value) {
        ...
    }
}
reko_t
myDic[someKey] already returns a Value of type Dictionary<int, User>. I think you should take out the "[someKey]".
Jeff Meatball Yang
Using myDic[someKey].Values would probably be cleaner.
Brian
A: 
//given: Dictionary<int, Dictionary<int, User>> myDic

foreach(KeyValuePair<int, Dictionary<int, User>> kvp in myDic) {
   foreach(KeyValuePair<int, User> kvpUser in kvp.Value) {
      User u = kvpUser.Value;
   }
}
Jeff Meatball Yang
+5  A: 

nested foreach

foreach (var keyValue in myDic){
   foreach (var user in keyValue.Value){
     ....
   }
}

or a bit of linq

        foreach (User User in myDic.SelectMany(i => i.Value).Select(kv=>kv.Value))
        {

        }

ordered by UserName

        foreach (User User in myDic.SelectMany(i => i.Value)
                                   .Select(kv=>kv.Value)
                                   .OrderBy(u=>u.UserName))
        {

        }
almog.ori
How about ordering my User.Username for the win?
mrblah
+1 Nicely done.
AnthonyWJones
Great! why the .selectmany and then .select ?
mrblah
SelectMany projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. Then we select the Value from each keyValuePair (which happens to be User)
almog.ori
+1  A: 

Are you looking for this ?

    var myDic = new Dictionary<int, Dictionary<int, string>>();
    foreach(var item in myDic)
        foreach (var subItem in item.Value)
        {
            Display(
                subItem.Key,    // int
                subItem.Value); // User
        }
Manitra Andriamitondra
+2  A: 
foreach(User user in myDic[someKey].Values)

Is the literal answer to your question; though I'd generally recommend the use of the TryGet method unless you're certain that someKey is in the Keys collection of your dictionary.

FacticiusVir
A: 
var users = myDic.Select(kvp => kvp.Value).SelectMany(dic => dic.Values);
foreach(User user in users)
{
   ...
}
Thomas Levesque