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]??)
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]??)
foreach (KeyValuePair<int, Dictionary<int, User>> users in myDic) {
foreach (KeyValuePair<int, User> user in users.Value) {
...
}
}
//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;
}
}
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))
{
}
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
}
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.
var users = myDic.Select(kvp => kvp.Value).SelectMany(dic => dic.Values);
foreach(User user in users)
{
...
}